MySQL Joing两个具有计数值的表

时间:2018-02-22 04:47:23

标签: mysql sql join

我有以下两个表和查询:

 select UserId,UserName, from ch_userregistration 

 select  ReceiverId, COUNT(Message) from ch_singleconversation WHERE 
 SenderId = '1002' AND MsgStatus='Y' GROUP BY ReceiverId

第一张表喜欢,

UserId  UserNeme`
-----------------
1001    Mohan
1002    Raj
1003    Mahesh
1004    rahul

第二张表赞成

ReceiverId    Count
---------------------------
 1002           8
 1004           4

我想要这样的结果

UserId   UserName   Count
----------------------------
1001    Mohan        0
1002    Raj          8
1003    Mahesh       0
1004    rahul        4

2 个答案:

答案 0 :(得分:1)

使用外部类型加入专门LEFT JOIN,因为您希望显示表ch_userregistration中的所有行,即使它在表ch_singleconversation中没有匹配项。

SELECT  a.UserId, 
        a.UserName,
        COUNT(b.Message) AS `Count`
FROM    ch_userregistration a
        LEFT JOIN ch_singleconversation b
            ON  b.senderId = '1002' 
                AND b.MsgStatus = 'Y'
                AND a.UserId = b.ReceiverId
GROUP   BY a.UserId, a.UserName

答案 1 :(得分:0)

您只需join来自带有子查询的两个查询的数据:

SELECT A.UserId, A.UserName, B.MessageCount
FROM
   (SELECT UserId, UserName 
    FROM ch_userregistration) A
LEFT JOIN
   (SELECT ReceiverId, COUNT(Message) MessageCount
    FROM ch_singleconversation 
    WHERE 
    SenderId='1002' AND MsgStatus='Y' 
    GROUP BY ReceiverId) B
ON A.UserId=B.ReceiverId;

或者:

SELECT A.UserId, A.UserName, B.MessageCount
FROM
   ch_userregistration A
LEFT JOIN
   (SELECT ReceiverId, COUNT(Message) MessageCount
    FROM ch_singleconversation 
    WHERE 
    SenderId='1002' AND MsgStatus='Y' 
    GROUP BY ReceiverId) B
ON A.UserId=B.ReceiverId;

OR:

SELECT A.UserId, A.UserName, COUNT(B.Message) MessageCount
FROM
   ch_userregistration A
LEFT JOIN
   ch_singleconversation B
ON A.UserId=B.ReceiverId
WHERE B.SenderId='1002' AND B.MsgStatus='Y' 
GROUP BY A.UserId, A.UserName;