我有一张表likes
,其中ID1喜欢ID2
ID1 ID2
1025 1101
1247 1468
1316 1304
1501 1934
1641 1468
1689 1709
1709 1689
1782 1709
1911 1247
1934 1501
所以我选择那些喜欢彼此的人,就是这个例子
1501 1934
1934 1501
但我想只选择一对,我无法做到。谁能指出我正确的方向?它是一个更大的查询的一部分,但这部分我无法做到。
由于
答案 0 :(得分:6)
要获得所有回复喜欢的明确列表,您可以使用
SELECT ID1,
ID2
FROM likes L1
WHERE ID1 > ID2
AND EXISTS(SELECT *
FROM likes L2
WHERE L1.ID1 = L2.ID2
AND L1.ID2 = L2.ID1)
答案 1 :(得分:0)
select
L1.ID1, L1.ID2
from likes L1
where exists
(select 1
from likes L2
where L1.ID1 = L2.ID2 and L1.ID2 = L2.ID1)
答案 2 :(得分:0)
修复数据:
SELECT ID1, ID2
FROM likes
WHERE ID1 < ID2
UNION
SELECT ID2 AS ID1, ID1 AS ID2
FROM likes
WHERE ID1 > ID2;
...然后通过向表中添加数据完整性约束来修复泄漏,例如
CREATE TABLE likes
(
ID1 INTEGER NOT NULL,
ID2 INTEGER NOT NULL,
CHECK (ID1 < ID2),
UNIQUE (ID1, ID2)
);
答案 3 :(得分:0)
SELECT L1.ID1, L1.ID2 FROM Likes L1, Likes L2
WHERE L1.ID1=L2.ID2 AND L1.ID2=L2.ID1 AND L1.ID1>L1.ID2