mysql计算where子句中给出的所有id,并计算其余的剩余部分

时间:2015-09-09 09:52:30

标签: mysql symfony doctrine-orm

我想要一个列表,我可以在where子句中查看我的给定ID的数量,剩下的ID的余数在这里是我的查询:

Select cat.name AS name, COUNT(cat.name) AS total
FROM MyAppBundle:Content c INNER JOIN c.category cat
WHERE cat.id IN(11,7,16,1,12,13)
GROUP BY cat.name;

但不知道如何获得剩下的总数,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您可以合并SUMCASE来获取匹配和非匹配计数:

SELECT cat.name AS name,
    SUM(CASE WHEN ID IN (11,7,16,1,12,13) THEN 1 ELSE 0) AS countMatch,
    SUM(CASE WHEN ID NOT IN (11,7,16,1,12,13) THEN 1 ELSE 0) AS countNotMatch
FROM MyAppBundle:Content c INNER JOIN c.category cat
GROUP BY cat.name

答案 1 :(得分:0)

您可以使用UNION ALL:

Select cat.name AS name, COUNT(cat.name) AS total 
FROM MyAppBundle:Content c INNER JOIN c.category cat 
WHERE cat.id IN(11,7,16,1,12,13)  
GROUP BY cat.name
UNION ALL
Select 'OTHERS' AS name, COUNT(cat.name) AS total 
FROM MyAppBundle:Content c INNER JOIN c.category cat 
WHERE cat.id NOT IN(11,7,16,1,12,13)