[英]How to find all the opposite combinations between two columns in SQL
我正在制作一個網絡約會應用,該應用需要匹配用戶並讓他們彼此聊天。
我想弄清楚如何查找特定用戶的所有匹配項。
現在,我有一個名為follow的表,該表具有2列。
UserID | MatchUserID
--------------------
1 | 2
2 | 1
1 | 3
1 | 4
1 | 5
4 | 1
5 | 4
這個想法是讓兩個用戶匹配,他們需要彼此關注。 上表顯示了哪個用戶關注哪個用戶。
假設當前登錄的用戶是UserID =1。我需要一個查詢,該查詢將從MatchUserID表返回以下結果:
2 4
在某種程度上,我希望找到兩列之間所有相反的組合。
這是我用來創建表的代碼。
CREATE TABLE Match
(
UserID INT NOT NULL,
MatchUserID INT NOT NULL,
PRIMARY KEY (UserID, MatchUserID)
);
最簡單的方法可能是使用EXISTS
和搜索其他匹配項的相關子查詢。
SELECT t1.matchuserid
FROM elbat t1
WHERE t1.userid = 1
AND EXISTS (SELECT *
FROM elbat t2
WHERE t2.matchuserid = t1.userid
AND t2.userid = t1.matchuserid);
您可以通過自我加入來實現:
select m.MatchUserID
from `Match` m inner join `Match` mm
on mm.MatchUserID = m.UserId
where
m.UserId = 1
and
m.MatchUserID = mm.UserId
參見演示 。
結果:
| MatchUserID |
| ----------- |
| 2 |
| 4 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.