简体   繁体   English

使用子选择作为返回列

[英]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. 例如,我正在使用MySql,并且我有一个表,其中包含与某些数据相关的ID列表。 I would like to convert the IDs associated with a given item of data from another table into a comma delimited VarChar list. 我想将与给定数据项关联的ID从另一个表转换为以逗号分隔的VarChar列表。 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. 但是,问题在于,我需要在另一个SELECT语句中以及存储过程中来自StudentTable的其他数据(例如)中返回该数据。 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. 在MySQL中甚至更容易。 Check out the GROUP_CONCAT function. GROUP_CONCAT函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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