如何在MySQL中使用case语句

时间:2012-05-15 11:33:43

标签: mysql

我使用where条件在mysql语句中使用三个查询 例如,如何将其作为单个查询

SELECT COUNT(*) as A FROM tbl_user WHERE (b=1 AND c=0)  AND (d=1 AND e=1)
SELECT COUNT(*) as M FROM tbl_user WHERE (H=1 AND I=0)  AND (J=1 AND K=1)

2 个答案:

答案 0 :(得分:1)

SELECT 
sum(case when (b=1 AND c=0)  AND (d=1 AND e=1) then 1 else 0 end) as CountA,
sum(case when (H=1 AND I=0)  AND (J=1 AND K=1) then 1 else 0 end) as CountM
 FROM tbl_user 

答案 1 :(得分:0)

您不需要CASE语句来执行此操作(尽管如果条件包含IF s),意图可能比使用OR更容易阅读最好使用IF传达

SELECT SUM(IF(b=1 AND c=0 AND d=1 AND e=1, 1, 0)) AS A,
       SUM(IF(H=1 AND I=0 AND J=1 AND K=1, 1, 0)) AS M
FROM tbl_user