Reputation: 580
Is it possible to use a subselect as one of the returned columns of a query?
For example, I am using MySql, and I have a table containing a list of IDs associated with some data. I would like to convert the IDs associated with a given item of data from another table into a comma delimited VarChar list. I know I can do that using something along the lines of:
DECLARE pr_StudentId INT; -- An input parameter
DECLARE @Classes VARCHAR(4096);
SELECT @Classes = COALESCE(@Classes + ',', '') + ClassTable.ClassId
FROM ClassTable, StudentTable
WHERE ClassTable.Id = StudentTable.Id
AND StudentTable.Id = p_StudentId;
However, the problem is that I need to return that within another SELECT along with other data from (for example) the StudentTable, which is in a stored procedure. So far I have this, but I'm not quite sure how to get it working:
SELECT
StudentTable.Id,
StudentTable.Name,
(
SELECT @Classes
FROM
(
SELECT @Classes = COALESCE(@Classes + ',','') + ClassTable.ClassId
FROM ClassTable, StudentTable
WHERE ClassTable.Id = StudentTable.Id
)
) AS ClassList,
...
FROM StudentTable ....
WHERE ....
Can anyone shed some light on whether this is the correct way to do this, if there is a better way, or if it is even possible?
Many thanks in advance.
Upvotes: 0
Views: 106
Reputation: 135818
It's even easier in MySQL. Check out the GROUP_CONCAT function.
SELECT st.Id, st.Name, GROUP_CONCAT(ct.ClassId) AS ClassList
FROM StudentTable st
INNER JOIN ClassTable ct
ON st.Id = ct.Id
GROUP BY st.Id, st.Name
Upvotes: 2