是否可以在单个查询中计算两行?现在我正在使用两个查询:
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 = ?
我想将这两个查询合二为一,可以吗?
SELECT SUM(published) AS publishedCount,
SUM(draft) AS draftCount
FROM projects
WHERE user_id = ?
据我了解您的查询,published
和的值draft
分别1
代表真和0
假。所以你可以SUM
让他们得到相同的结果。
尝试这个
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 = ?
尝试联合:
(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);