請考慮以下內容......本示例假設通過每個友誼插入兩行來確定往復。然而,爲了簡單起見,下面的例子並沒有檢查友誼是否有回報!
DROP TABLE IF EXISTS friends;
CREATE TABLE friends
(initiator VARCHAR(12) NOT NULL
,reciprocator VARCHAR(12) NOT NULL
,PRIMARY KEY (initiator,reciprocator)
);
INSERT INTO friends VALUES
('Adam','Ed'),
('Ed','Adam'),
('Adam','Ben'),
('Ben','Adam'),
('Adam','Charlie'),
('Charlie','Adam'),
('Adam','Dan'),
('Dan','Adam'),
('Ed','Ben'),
('Ben','Ed'),
('Ben','Charlie'),
('Charlie','Ben'),
('Charlie','Dan'),
('Dan','Charlie'),
('Dan','Fred'),
('Fred','Dan'),
('Adam','Fred'),
('Fred','Adam');
要獲得所有奔的「的朋友 - 的 - 朋友」,我們可以做到這一點的列表...
SELECT y.reciprocator
FROM friends x
JOIN friends y
ON y.initiator = x.reciprocator
AND y.reciprocator <> x.initiator
LEFT
JOIN friends z
ON z.reciprocator = y.reciprocator
AND z.initiator = x.initiator
WHERE x.initiator = 'Ben'
AND z.initiator IS NULL;
+--------------+
| reciprocator |
+--------------+
| Dan |
| Fred |
| Dan |
+--------------+
正如你所看到的,因爲丹是朋友亞當和查理(本的朋友)他的名字出現了兩次。
因此,要獲得DISTINCT朋友朋友列表,只需包含DISTINCT運算符。
同樣,獲得個人誰是陌生人本名單,但至少兩個本的朋友的朋友,我們可以做到這一點...
SELECT y.reciprocator
FROM friends x
LEFT
JOIN friends y
ON y.initiator = x.reciprocator
AND y.reciprocator <> x.initiator
LEFT
JOIN friends z
ON z.reciprocator = y.reciprocator
AND z.initiator = x.initiator
WHERE x.initiator = 'Ben'
AND z.initiator IS NULL
GROUP
BY y.reciprocator
HAVING COUNT(*) >= 2;
+--------------+
| reciprocator |
+--------------+
| Dan |
+--------------+
可能有處理的幾種方法這個問題的相互作用方面,正如處理互惠本身的幾種方式一樣。
一種方法是用一個簡單的子查詢替換上述每個出現的friends
表,
SELECT y.reciprocator
FROM (SELECT a.* FROM friends a JOIN friends b ON b.reciprocator = a.initiator AND b.initiator = a.reciprocator) x
LEFT
JOIN (SELECT a.* FROM friends a JOIN friends b ON b.reciprocator = a.initiator AND b.initiator = a.reciprocator) y
ON y.initiator = x.reciprocator
AND y.reciprocator <> x.initiator
LEFT
JOIN (SELECT a.* FROM friends a JOIN friends b ON b.reciprocator = a.initiator AND b.initiator = a.reciprocator) z
ON z.reciprocator = y.reciprocator
AND z.initiator = x.initiator
WHERE x.initiator = 'Ben'
AND z.initiator IS NULL
GROUP
BY y.reciprocator
HAVING COUNT(*) >= 2;
不需要使用MySQL。你如何對待互惠? – Strawberry
Whell ..我不...任何建議如何我可以修改這個查詢來檢查,如果我也是我的朋友的朋友? – PsychoX