mysql - 为什么条件不起作用?

时间:2016-04-02 08:09:19

标签: mysql

SELECT
    t1.user_id,
    count(*) total,
    sum(case when t1.var1 = 'yes' then 1 else 0 end) as type1,
    sum(case when t1.var1 = 'no' then 1 else 0 end) as type2
FROM table as t1
WHERE type1 > 0
GROUP by t1.user_id
ORDER by type1 DESC
LIMIT 100

结果我得到行:

user_id  total  type1  type2
  1       100    80     20
  4       120    70     50
  6       90     0      90

请告诉我为什么条件WHERE type1 > 0不起作用以及如何选择具有此条件的行?

1 个答案:

答案 0 :(得分:1)

WHERE仅适用于原始值,而不适用于您刚刚将其他值相加的变量,您可以使用HAVING

SELECT
t1.user_id,
count(*) total,
sum(case when t1.var1 = 'yes' then 1 else 0 end) as type1,
sum(case when t1.var1 = 'no' then 1 else 0 end) as type2
FROM table as t1
GROUP by t1.user_id
HAVING type1 > 0
ORDER by type1 DESC
LIMIT 100

有关使用HAVINGhttp://www.w3schools.com/sql/sql_having.asp

的另一个示例,请参阅此处
相关问题