如何在其他子查询中使用一个子查询的结果集

时间:2014-11-11 18:22:35

标签: mysql sql nested

我有以下mysql查询:

SELECT 
    ec.id, 
    ec.name, 
    gecr.Group_Id, 
    (SELECT 
        COUNT(DISTINCT c.ID) 
        FROM containers c 
        WHERE c.group_id IN (
                    SELECT g.ID AS Group_id FROM (group_master g) 
                    INNER JOIN group_user_reln gur ON g.ID = gur.group_id
                    WHERE gur.user_id =  91))
        AS group_count
    FROM 
        exam_category ec 
    INNER JOIN 
        group_exam_category_reln gecr ON gecr.Exam_category_Id = ec.ID 
    WHERE 
        ec.InActive_YN =  'N' 
        AND gecr.Group_Id IN 
        (SELECT g.ID AS Group_id FROM (group_master g) 
    INNER JOIN group_user_reln gur ON g.ID = gur.group_id
    WHERE gur.user_id =  91) 
    GROUP BY ec.id
    ORDER BY ec.name asc

在上面的查询中,如何使用子查询仅获取组ID一次?

1 个答案:

答案 0 :(得分:0)

将变量声明为表

   DECLARE @ids TABLE (id INT)

用数据填充此表

  INSERT INTO @ids SELECT g.ID AS Group_id FROM (group_master g)

在查询中使用它。这是一种TSQL语法,但在MySql中也应该类似。