1

有没有一些有效的方法来编写查询,将 GROUP BY 的各种结果连接到一个公共表上?MySQL如何处理子GROUP上聚合函数的合并结果与原始表中的完整字段?

我正在使用它并且它很慢(而且我还需要除 CONDITION=1 之外的其他条件)

SELECT a.CID,a.AS_ALL,b.AS_ACTIVE FROM 
            (SELECT CID,COUNT(DISTINCT RAID) AS AS_ALL FROM MYTABLE GROUP BY CID) a
            LEFT JOIN
            (SELECT CID,COUNT(DISTINCT RAID) AS AS_ACTIVE FROM MYTABLE WHERE CONDITION=1 GROUP BY CID ) b ON a.CID=b.CID;

也可以节省使用类似的东西吗?MySQL 将始终正确地将 COLUMN_A 与聚合结果合并吗?

SELECT  COLUMN_A COUNT(DISTINCT COLUMN_A), SUM(COLUMN_A),SUM(COLUMN_B) FROM ATABLE WHERE CONDITION=1 GROUP BY COLUMN_C 

谢谢你的建议

4

1 回答 1

0

试试这个:

SELECT CID,COUNT(DISTINCT RAID) AS AS_ALL,SUM(IF(CONDITION=1, 1, 0)) AS AS_ACTIVE 
FROM MYTABLE GROUP BY CID
于 2012-11-27T13:28:30.913 回答