简体   繁体   中英

Using a Sub-Select as a Returned Column

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM