如何使用左连接选择涉及当前用户的对话

时间:2016-08-08 03:14:05

标签: php mysql

以下查询选择会话参与者的总数,但列出所有相同的会话:

$id = 4;
$query = 'SELECT COUNT(1)'
       + ' FROM tbl_conversations AS a'
       + ' LEFT JOIN tbl_conversations_participants AS b'
       + ' ON a.id = b.conversation_id';

如果我添加此内容:WHERE b.user_id = $id;它会显示正确的会话数,但会列出所有相同的会话。

对话表:

Conversations Table

与会者表:

Participants Table

2 个答案:

答案 0 :(得分:0)

您可能正在寻找参加特定对话的参与者人数。

SELECT 
COUNT(DISTINCT b.user_id) totalParticipants
FROM tbl_conversations AS a
INNER JOIN tbl_conversations_participants AS b
ON a.id = b.conversation_id
WHERE a.id = 4;

如果您只需要计数,则以下查询就足够[无需涉及tbl_conversations]:

SELECT 
COUNT(DISTINCT user_id) totalParticipants
FROM tbl_conversations_participants 
WHERE conversation_id = 4;

如果您想知道每次对话的总参与者数:

SELECT
 a.id, 
 COUNT(DISTINCT b.user_id) totalParticipants
FROM tbl_conversations AS a
LEFT JOIN tbl_conversations_participants AS b
ON a.id = b.conversation_id
GROUP BY a.id

答案 1 :(得分:0)

我不明白。

为什么要使用2个表格( tbl_conversation tbl_conversations_participants ),如果您只想知道与特定用户的会话次数,请仅使用 tbl_conversations_participants 然后计算不同的 conversation_id

查询看起来像:

SELECT COUNT(DISTINCT a.conversation_id) AS count_conversation
FROM tbl_conversations_participants a
WHERE a.user_id = $id