1

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

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 = ?

我想将这两个查询合二为一,可以吗?

4

3 回答 3

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

据我了解您的查询,published和的值draft分别1代表真和0假。所以你可以SUM让他们得到相同的结果。

于 2013-05-20T16:50:45.683 回答
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 = ?
于 2013-05-20T16:51:37.660 回答
0

尝试联合:

(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);
于 2013-05-20T16:54:47.103 回答