将2个计数与同一个表中的不同位置组合在一起

时间:2021-08-02 00:49:27

Is there a better way of doing this ?

有更好的方法吗?

SELECT
  (SELECT count(*) FROM `tbl` WHERE `status` = 0) as 'text1',
  (SELECT count(*) FROM `tbl` WHERE `status` > 0) as 'text2'

text1 and text2 are headers.

text1和text2是标题。

4 个解决方案

#1


How about

select sum(if(status=0,1,0)) as zeros, 
       sum(if(status>0,1,0)) as greater 
from tbl;

Might not necessarily be better, but it's a useful idiom to have in your mental arsenal!

可能不一定更好,但它在你的心理武器库中是一个有用的成语!

#2


I vote for using two different queries for the sake of simplicity and improved code readability. There isn't much benefit of using a clever hack to combine the queries, when you can achieve the same result and more readable code by having two queries,

为了简单起见和改进的代码可读性,我投票赞成使用两个不同的查询。使用聪明的hack来组合查询没什么好处,当你通过两个查询可以实现相同的结果和更易读的代码时,

#3


Here's another way:

这是另一种方式:

SELECT
  COUNT(NULLIF(`status` = 0, 0)),
  COUNT(NULLIF(`status` > 0, 0))
FROM `tbl`

#4


This gives you a different output, but sorta works:

这给你一个不同的输出,但sorta工作:

SELECT `status` > 0 AS 'stat', COUNT( * )
FROM `tbl`
GROUP BY stat

Output:

stat | COUNT(*)
-------------------------------
 0   | (count where status = 0)
 1   | (count where status > 0)

#1


How about

select sum(if(status=0,1,0)) as zeros, 
       sum(if(status>0,1,0)) as greater 
from tbl;

Might not necessarily be better, but it's a useful idiom to have in your mental arsenal!

可能不一定更好,但它在你的心理武器库中是一个有用的成语!

#2


I vote for using two different queries for the sake of simplicity and improved code readability. There isn't much benefit of using a clever hack to combine the queries, when you can achieve the same result and more readable code by having two queries,

为了简单起见和改进的代码可读性,我投票赞成使用两个不同的查询。使用聪明的hack来组合查询没什么好处,当你通过两个查询可以实现相同的结果和更易读的代码时,

#3


Here's another way:

这是另一种方式:

SELECT
  COUNT(NULLIF(`status` = 0, 0)),
  COUNT(NULLIF(`status` > 0, 0))
FROM `tbl`

#4


This gives you a different output, but sorta works:

这给你一个不同的输出,但sorta工作:

SELECT `status` > 0 AS 'stat', COUNT( * )
FROM `tbl`
GROUP BY stat

Output:

stat | COUNT(*)
-------------------------------
 0   | (count where status = 0)
 1   | (count where status > 0)