如果重寫2查詢與EXISTS
而不是加入,您可以先刪除DISTINCT
(我假設uid
這裏是Users
的主鍵),第二,INTERSECT
和EXCEPT
(也稱爲MINUS
)操作是清楚的:
查詢1:
SELECT U.uid
FROM users U
WHERE U.status = '1'
AND EXISTS
(SELECT *
FROM friends F
WHERE U.uid = F.friend_two
AND F.friend_one = '1'
AND F.ROLE = 'fri'
) ;
問題2:
SELECT U.uid
FROM users U
WHERE U.status = '1'
AND EXISTS
(SELECT *
FROM friends F
WHERE U.uid = F.friend_one
AND F.friend_two = '1'
AND F.ROLE = 'fri'
) ;
問題3:INTERSECT
SELECT U.uid
FROM users U
WHERE U.status = '1'
AND EXISTS
(SELECT *
FROM friends F
WHERE U.uid = F.friend_two
AND F.friend_one = '1'
AND F.ROLE = 'fri'
)
AND EXISTS
(SELECT *
FROM friends F
WHERE U.uid = F.friend_one
AND F.friend_two = '1'
AND F.ROLE = 'fri'
) ;
查詢4:EXCEPT
(MINUS
)
SELECT U.uid
FROM users U
WHERE U.status = '1'
AND EXISTS
(SELECT *
FROM friends F
WHERE U.uid = F.friend_two
AND F.friend_one = '1'
AND F.ROLE = 'fri'
)
AND NOT EXISTS -- notice the NOT here
(SELECT *
FROM friends F
WHERE U.uid = F.friend_one
AND F.friend_two = '1'
AND F.ROLE = 'fri'
) ;
這兩個查詢都是**相同**。他們真的在每次運行中返回不同數量的行嗎? – krokodilko
不,他們不是,'friend_one'和'friend_two'被替換。 –