Mysql全外连接3个表with group by和count

时间:2014-11-11 23:09:55

标签: mysql

我的查询只显示了为我发送消息的人的记录子集,而我想返回所有用户的列表,他们是否有消息给我或不带有计数(或者是真/假,0,1 )

SELECT attendee.id, attendee.firstName, attendee.lastName, count(attendee_chat.to) 
from attendee_chat
INNER JOIN attendee ON attendee.id = attendee_chat.to
INNER JOIN chat ON attendee_chat.id = chat.attendee_chat_id
WHERE attendee.id <> 1
GROUP BY attendee_chat.to;
图片胜过千言万语。

enter image description here

2 个答案:

答案 0 :(得分:0)

如果你想对记录进行连接,即使它们在另一个关系中没有匹配的元素,你可能想要一个OUTER JOIN而不是INNER JOIN。

MySQL: Quick breakdown of the types of joins

答案 1 :(得分:0)

将与会者表放在FROM中,然后将其连接到其他可能没有记录的表。

SELECT attendee.id, attendee.firstName, attendee.lastName, count(attendee_chat.to) 
from attendee 
LEFT JOIN attendee_chat ON attendee_chat.to = attendee.id
LEFT JOIN chat ON attendee_chat.id = chat.attendee_chat_id
WHERE attendee.id <> 1
GROUP BY attendee_chat.to;

我会避免做一个完整的外部连接,因为它没有必要,可能会导致一些意想不到的结果。

编辑:试试这个。删除chat表,因为您还没有选择它,并对主表attendee中的字段进行分组,而不是可能不包含任何数据的表。

SELECT attendee.id, attendee.firstName, attendee.lastName, count(attendee_chat.to) 
from attendee 
LEFT JOIN attendee_chat ON attendee_chat.to = attendee.id
WHERE attendee.id <> 1
GROUP BY attendee.id, attendee.firstName, attendee.lastName;

EDIT2:在讨论了他想要对他进行聊天的要求之后(#1)

SELECT attendee.id, attendee.firstName, attendee.lastName, 
(SELECT count(1) FROM attendee_chat 
   WHERE attendee_chat.from = attendee.id and  attendee_chat.to = 1) as chatcount
 from attendee ;

EDIT3:关于外部ID的评论后

SELECT attendee.id, attendee.firstName, attendee.lastName, attendee.attendee_id,
(SELECT count(1) FROM attendee_chat 
    INNER JOIN attendee a2 ON a2.id = attendee_chat.toid
    WHERE attendee_chat.fromid = attendee.id and a2.attendee_id = 123
) as chatcount
FROM attendee ;

P.S。我已经从toid改为 - &gt;使用保留字作为对象名称是危险的;-) SQL Fiddle here