是否可以在单个查询中计算两行?现在我正在使用两个查询:
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 = ?
我想将这两个查询合并为一个可能吗?
答案 0 :(得分:2)
SELECT SUM(published) AS publishedCount,
SUM(draft) AS draftCount
FROM projects
WHERE user_id = ?
据我了解您的查询,published
和draft
的值为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);