2016-03-06 46 views
4

我有如下表:如何列出多個領域從單一的表在Oracle SQL匹配

create table Likes(ID1 number(5), ID2 number(5)); 
insert into Likes values(1689, 1709); 
insert into Likes values(1709, 1689); 
insert into Likes values(1782, 1709); 
insert into Likes values(1911, 1247); 
insert into Likes values(1247, 1468); 
insert into Likes values(1641, 1468); 
insert into Likes values(1316, 1304); 
insert into Likes values(1501, 1934); 
insert into Likes values(1934, 1501); 
insert into Likes values(1025, 1101); 

表包含了由它們的ID識別用戶的「喜歡」。喜歡是單向連接(如果ID1喜歡ID2並不意味着TD2喜歡ID1)。

我想找到這些ID,其中是雙向連接(其中'liker'是'喜歡',由用戶喜歡)。

我是初學者與Oracle SQL,我希望我的問題是不是平庸......

+0

是否有解決方案,「類似連接」在輸出中不重複? – dsz36

回答

4

你可以做一個連接:

SELECT t.id1,t.id2 
FROM Likes t 
INNER JOIN Likes s 
ON(t.id1 = s.id2 and t.id2 = s.id1) 

或用EXISTS()

SELECT t.* 
FROM Likes t 
WHERE EXISTS(select 1 FROM Likes s 
      WHERE t.id1 = s.id2 
       AND t.id2 = s.id1) 
+0

我真的很感謝你的回答。我學到了很多。謝謝! – dsz36

+0

沒問題m8 @ dsz36 – sagi

3

只有在表中存在其他記錄的情況下,您需要選擇給定的記錄id1 = X,id2 = Y,
其中id1 = Y,id2 = X。
像這樣的情況可以在SQL中表示與EXISTS操作和相關子查詢的幫助:

SELECT * 
FROM likes t 
WHERE EXISTS (
    SELECT 1 FROM likes t1 
    WHERE t.id1 = t1.id2 AND t.id2 = t1.id1 
) 
+0

感謝您的解釋!我看了,閱讀並嘗試了3個教程,我錯過了EXISTS()命令。 – dsz36

3

試試這個:

with tab as (select id1, id2 from Likes) 
select id1, id2 from tab 
intersect 
select id2, id1 from tab; 

應該有更好的表現,原因是其會閱讀Likes表只有一次

+0

特別感謝這第三個解決方案!我學到了另一件新事物! – dsz36

+0

總是樂於幫忙 – MaxU

3

使用此查詢:

 SELECT 
      id1, id2 from Likes L1 
     INNER JOIN (
      Select id1, id2 from Likes 
     ) as L2 
     on (L1.id1 = L2.id) 
WHERE L1.id2 = L2.id1 
+0

謝謝大家! <3 – dsz36