mysql using user-defined variable in where clause

你离开我真会死。 提交于 2019-12-10 23:16:34

问题


sql query:

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

if i remove where @total_subscribers > 0 query will show all users and their total subscribers

but i want to show only those users who have at least 1 subscriber... after i add the where clause and use the defined variable i get an empty result set.


回答1:


You can do it with group by and 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



回答2:


MySQL does not guarantee the order of evaluation of the session variables in this case.

From the docs:

The order of evaluation for expressions involving user variables is undefined and may change based on the elements contained within a given statement; in addition, this order is not guaranteed to be the same between releases of the MySQL Server

Use this:

SELECT  u.*, COUNT(*)
FROM    users u
JOIN    subscribers s
ON      s.suid = u.uid
GROUP BY
        u.uid

The JOIN makes sure you have at least one subscriber.



来源:https://stackoverflow.com/questions/10934939/mysql-using-user-defined-variable-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!