我有一张这样的桌子:
-----------------------------------------
id | user_id | done | created_at
-----------------------------------------
1 | 5 | 0 | 2017-12-23 23:28:00
1 | 2 | 1 | 2017-12-23 23:28:00
1 | 5 | 1 | 2017-12-23 23:28:00
1 | 10 | 0 | 2017-12-23 23:28:00
1 | 7 | 0 | 2017-12-23 23:28:00
1 | 5 | 1 | 2017-12-23 23:28:00
我想得到的是至少有一个done
为0的用户数(请注意,user_id列值可以重复多次)
我试过了:
select count(*) as sum from users group by user_id having done=0
但它说Unknown column 'done' in 'having clause'
如何使用MySQL获取正确的数据?
答案 0 :(得分:2)
要获得至少有一个完成= 0的用户,您可以使用以下
select count(*) as sum
from users
group by user_id
having sum(done=0) > 0
获取至少有一条记录的所有用户的计数,其中done = 0
select count(distinct user_id)
from users
where done=0;
答案 1 :(得分:1)
尝试这个
使用where
代替having
select count(*) as sum from users where done=0 group by user_id