我想顯示用戶“A”關注的所有用戶資料。然后進一步檢查用戶“B”是否也在關注用戶“A”的某些用戶。
我設法獲取了用戶“A”關注的所有用戶資料。但是不明白如何查詢第二個條件。
這是我的小提琴鏈接示例:https ://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=29a7d1e29f794a8f18a89fe45c06eaa9
uj5u.com熱心網友回復:
您可以嘗試讓您的用戶'B'進入子查詢然后執行 OUTER JOIN
SELECT u.*,
IF(friend_id IS NULL,0,1) amIfollowing
FROM users u
LEFT JOIN (
Select friend_id
from friends
where user_id = 5
) f ON f.friend_id = u.id
WHERE u.id IN (SELECT f.friend_id
FROM friends f
WHERE f.user_id = 1)
ORDER BY u.id
sqlfiddle
如果我理解正確,您可以嘗試只使用一個子查詢friends,然后使用條件聚合函式來獲取結果。
SELECT u.id,
u.image_width,
MAX(CASE WHEN f.user_id = 5 THEN 1 ELSE 0 END) amIfollowing
FROM users u
JOIN (
Select friend_id,user_id
from friends
where user_id IN (1,5)
) f ON f.friend_id = u.id
GROUP BY u.id,
u.image_width
ORDER BY u.id
uj5u.com熱心網友回復:
您可以在此處使用exists來檢查相應的 ID 是否存在:
SELECT *,
case when exists (
select * from friends f
where f.friend_id = u.id and f.user_id = 5
) then 1 else 0 end amIfollowing
FROM users u
WHERE u.id IN (SELECT f.friend_id
FROM friends f
WHERE f.user_id = 1);
示例小提琴
uj5u.com熱心網友回復:
看起來像 JOIN 會做,有不同的
SELECT distinct u.*, (f2.user_Id is not null) amIfollowing
FROM users u
JOIN friends f ON u.id = f.friend_id
LEFT JOIN friends f2 on f2.friend_id = f.friend_id and f2.user_id = 5
WHERE f.user_id = 1
ORDER BY u.id
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/457821.html
上一篇:左連接后從另一個表中選擇列
