用if表示在单个表中并在两个单独的列中显示结果--mysql

时间:2014-11-18 22:12:55

标签: php mysql mysqli

我有像table-name perms这样的表,我需要获得结果,例如uid = 1和pid = 1,并将0作为counter1计数,并将1作为counter2计数

uid    pid  oid  value
 1      1    15    0
 1      1    17    1
 1      1    18    0

我可以像这样简单计算

SELECT *,count(*) as counter1 from perms where uid = 1 and pid = 1 and value = 0

如何在与单独列相同的查询中获取counter2

1 个答案:

答案 0 :(得分:1)

使用CASE条件,例如

select *,
sum(case when `value` = 0 then 1 else 0 end) as counter1,
sum(case when `value` = 1 then 1 else 0 end) as counter2
from perms 
where uid = 1 
and pid = 1;