出發點是聯盟都知道表:
SELECT personA_id ,
personB_id
FROM @k k
UNION
SELECT personB_id ,
personA_id
FROM @k k
因爲你會得到不正確的結果,如果你只是從一個側面驗證表知道了。
DECLARE @p TABLE
(
id INT ,
name NVARCHAR(MAX) ,
age INT
)
DECLARE @k TABLE
(
personA_id INT ,
personB_id INT
)
INSERT INTO @p
VALUES (1, 'a', 10),
(2, 'b', 14),
(3, 'c', 30),
(6, 'f', 35),
(7, 'g', 45)
INSERT INTO @k
VALUES (1, 2),
(1, 3),
(2, 3),
(7, 6)
SELECT t.personA_id ,
t.name
FROM (SELECT personA_id ,
name ,
paage - pbage AS diff
FROM (SELECT personA_id ,
personB_id ,
pa.age paage ,
pb.age pbage ,
pa.name
FROM @k k
JOIN @p pa ON pa.id = k.personA_id
JOIN @p pb ON pb.id = k.personB_id
UNION
SELECT personB_id ,
personA_id ,
pb.age pbage ,
pa.age paage ,
pb.name
FROM @k k
JOIN @p pa ON pa.id = k.personA_id
JOIN @p pb ON pb.id = k.personB_id
) k
) t
GROUP BY t.personA_id ,
t.name
HAVING (MIN(diff) > 5)
輸出:
personA_id name
3 c
7 g
如果您將直接加入上表誰知,那麼你將得到:
SELECT t.personA_id ,
t.name
FROM (SELECT personA_id ,
name ,
paage - pbage AS diff
FROM (SELECT personA_id ,
personB_id ,
pa.age paage ,
pb.age pbage ,
pa.name
FROM @k k
JOIN @p pa ON pa.id = k.personA_id
JOIN @p pb ON pb.id = k.personB_id
) k
) t
GROUP BY t.personA_id ,
t.name
HAVING (MIN(diff) > 5)
輸出:
personA_id name
7 g
它是如何不工作?你使用的是什麼RDBMS? – 2015-02-23 19:37:26
那麼爲什麼你的意思是「它不工作」? – Lamak 2015-02-23 19:42:50
我的意思是它沒有返回應有的東西。查詢看起來是否正確,我想返回? – eeKat88 2015-02-23 19:43:59