簡體   English   中英

SQL選擇多對多關系

[英]SQL select many to many relationship

我有以下架構:

Users
-----
id
name

Conversations
-------------
id
other

Partecipants (join table)
------------
id
user_id
conversation_id
other

一個用戶可以有很多對話,並且一個對話屬於許多用戶。

我需要選擇一個用戶與其他用戶的子集的所有對話。

我的嘗試是(不起作用):

SELECT     *
FROM       `conversations` 
INNER JOIN `participants` ON `conversations`.`id` = `participants`.`conversation_id` 
WHERE      `participants`.`user_id` = 1 
AND         (participants.user_id IN (4,6)) 
GROUP BY    participants.conversation_id 

任何想法?

嗯。 這是使用group byhaving

select p.conversation_id
from participants p
group by p.conversation_id
having sum(p.user_id = 1) > 0 and     -- user 1 in conversation
       sum(p.user_id in (4, 6)) > 0;   -- user 4 and/or 6 in conversation

從您的問題中我了解到的是,您希望看到與user_id = 1對話的用戶“ 4,6”。為此,請嘗試執行以下查詢。

 select * from (SELECT     conversations.id as conversation_id, participants.user_id as selectedUser,   GROUP_CONCAT(participants.user_id) AS participants
 FROM       `conversations` 
 INNER JOIN `participants` ON `conversations`.`id` = `participants`.`conversation_id` 
GROUP BY    participants.conversation_id ) as derivedTable 
where 
selectedUser=1 and 
(participants like '%4%' and participants like '%6%')

在此處輸入圖片說明

以上查詢的作用是。 最初,它將從對話和參與者表中獲取所有記錄,並再次將所有參與者連接到user_id = 1。 然后外部查詢檢查很清楚地找到了user_id,參與者有4和6。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM