如何使用' group by'在MySQL中有一个子查询?

时间:2018-01-30 12:33:01

标签: mysql sql

我有以下查询:

SELECT c.text1, sum(c.num1), sum(c.num2), sum(c.num3),
    (SELECT count(id) FROM table2 WHERE type = 1 AND txt = c.text1 AND spec_id = c.sp_id)
FROM table1 as c
WHERE c.type = 1
GROUP BY c.text1, c.sp_id

是否有解决方法以某种方式从GroupBy子句中松开c.sp_id?我知道如果我删除它,MySQL将返回错误。

或者是否有办法仅按c.text1对此查询的结果进行分组?

1 个答案:

答案 0 :(得分:2)

如果我正确理解了问题,您需要进行两次单独的聚合。这是查询的一个版本:

SELECT c.text1, c.sum1, c.sum2, c.sum3, t2.cnt
FROM (SELECT c.text1, sum(c.num1) as sum1, sum(c.num2) as cum2, sum(c.num3) as sum3
      FROM table1 c
      GROUP BY c.text1
     ) c LEFT JOIN
     (SELECT txt, count(*) as cnt
      FROM table2 t2
      WHERE t2.type = 1 AND
            EXISTS (SELECT 1
                    FROM table1 c2
                    WHERE t.txt = c2.txt AND c2.type = 1 AND
                          t.spec_id = c2.sp_id
                   )
     ) t2
     ON t2.txt = c.text1
WHERE c.type = 1;