admin

mysql在where子句中使用用户定义的变量

sql

sql查询:

select
    u.username,
        @total_subscribers:=(
            select count(s.id)
                from subscribers as s
                where s.suid = u.uid
        ) as total_subscribers
from users as u
where @total_subscribers > 0

如果我删除where @total_subscribers > 0查询,将显示所有用户及其总订阅者

但是我只想显示那些至少拥有1个订阅者的用户…在我添加where子句并使用定义的变量后,我得到一个空结果集。


阅读 298

收藏
2021-07-01

共1个答案

admin

您可以使用group by和进行操作having

select
   u.username,
   count(s.id) as total_subscribers
from users as u
inner join subscribers as s on s.suid = u.uid
group by u.id
having count(s.id) > 0
2021-07-01