I've got two tables:
TableA
------
ID,
Name
TableB
------
ID,
SomeColumn,
TableA_ID (FK for TableA)
The relationship is one row of TableA
- many of TableB
.
Now, I want to see a result like this:
ID Name SomeColumn
1. ABC X, Y, Z (these are three different rows)
2. MNO R, S
This won't work (multiple results in a subquery):
SELECT ID,
Name,
(SELECT SomeColumn FROM TableB WHERE F_ID=TableA.ID)
FROM TableA
This is a trivial problem if I do the processing on the client side. But this will mean I will have to run X queries on every page, where X is the number of results of TableA
.
Note that I can't simply do a GROUP BY or something similar, as it will return multiple results for rows of TableA
.
I'm not sure if a UDF, utilizing COALESCE or something similar might work?
Solution below:
Use this, you also can change the Joins
In MySQL there is a group_concat function that will return what you're asking for.
You may need to provide some more details for a more precise response.
Since your dataset seems kind of narrow, you might consider just using a row per result and performing the post-processing at the client.
So if you are really looking to make the server do the work return a result set like
which of course is a simple INNER JOIN on ID
Once you have the resultset back at the client, maintain a variable called CurrentName and use that as a trigger when to stop collecting SomeColumn into the useful thing you want it to do.
Assuming you only have WHERE clauses on table A create a stored procedure thus:
Then fill a DataSet ds with it. Then
Finally you can add a repeater in the page that puts the commas for every line
In this way you will do it client side but with only one query, passing minimal data between database and frontend
1. Create the UDF:
2. Use in subquery:
3. If you are using stored procedure you can do like this:
This will work for selecting from different table using sub query.