计算用户的消息,对2个表进行1次查询

时间:2016-03-29 08:04:06

标签: mysql sql database left-join

有2个表:

  1. 用户
  2. 消息
  3. 我想要计数状态为1且状态= 2的消息。这是我试图做的事情

    SELECT u.id_user, u.email, COUNT(m.id_message) as 'viewed', COUNT(m2.id_message) as 'not viewed'
    FROM users u
    LEFT JOIN messages m ON (u.id_user=m.id_user AND m.status=1)
    LEFT JOIN messages m2 ON (u.id_user=m2.id_user AND m2.status=2)
    GROUP BY u.id_user
    

    但结果很奇怪 enter image description here

    计数器'查看'并且'不是观看'可以是一样的。我做错了什么?

1 个答案:

答案 0 :(得分:1)

你可以为此

做条件和
select 
u.id_user,
u.email,
sum(case when m.status=1 then 1 else 0 end) as `viewed`,
sum(case when m.status=0 then 1 else 0 end) as `not viewed`
from users u
left join messages m on m.id_user = u.id_user
group by u.id_user,u.email