Mysql在单个查询中计算两行

时间:2013-05-20 16:45:19

标签: mysql count

是否可以在单个查询中计算两行?现在我正在使用两个查询:

SELECT count(draft) AS draftCount FROM projects WHERE draft = 1 AND user_id = ?

还有一个:

SELECT count(published) AS publishedCount FROM projects WHERE published = 1 AND user_id = ?

我想将这两个查询合并为一个可能吗?

3 个答案:

答案 0 :(得分:2)

SELECT SUM(published) AS publishedCount,
       SUM(draft) AS draftCount
FROM projects
WHERE user_id = ?

据我了解您的查询,publisheddraft的值为1为真,0为false。所以你可以SUM得到相同的结果。

答案 1 :(得分:2)

试试这个

SELECT count(case when draft = 1 then draft end) AS draftCount,
count(case when published = 1 then published end) AS publishedCount 
FROM projects 
WHERE user_id = ?

答案 2 :(得分:0)

尝试UNION:

(SELECT count(draft) FROM projects WHERE draft = 1 AND user_id = 4)
UNION
(SELECT count(published) FROM projects WHERE published = 1 AND user_id = 4);