您沒有提供該內容作者存儲領域,所以我會以爲這是content.author
:
SELECT *
FROM content
WHERE public = 1
OR
(
public = 3
AND EXISTS
(
SELECT NULL
FROM friends
WHERE userId = @me
AND friendID = content.author
)
)
,或者更好的是:
SELECT *
FROM content
WHERE public = 1
UNION ALL
SELECT *
FROM content
WHERE public = 3
AND EXISTS
(
SELECT NULL
FROM friends
WHERE userId = @me
AND friendID = content.author
)
,如果您author
場是有選擇性的,分類比過濾便宜。
還要注意的是,如果你的友誼是一個對稱的關係(即,如果一個userA
是朋友userB
,然後userB
是朋友userA
),它是在一個表像這樣更好的存儲:
userA userB
與檢查約束:
userA < user B
宥始終把用戶與至少id
第一。
在這種情況下,您的查詢是這樣的:
SELECT *
FROM content
WHERE public = 1
UNION ALL
SELECT *
FROM content
WHERE public = 3
AND EXISTS
(
SELECT NULL
FROM friends
WHERE userA = @me
AND userB = content.author
UNION ALL
SELECT NULL
FROM friends
WHERE userB = @me
AND userA = content.author
)