2015-08-18 30 views
1

我正在構建一個應用程序,旨在向用戶顯示一個隨機選擇的用戶列表,他/她可能會喜歡他們已經不在對方的列表。MYSQL - 隨機選擇一行,其中兩個用戶沒有跟蹤對方?

我有2個表格,一個表格有一個用戶列表,第二個表格有2列顯示「跟隨」關係。

表1用戶 - USER_ID,instagram_id,join_date

表2 users_follow - instagram_id_1,instagram_id_2

我只是想知道如果任何人都可以就如何創建指向正確的方向我加入並選擇一個隨機的行,其中2個用戶不相互關注?我已經嘗試了一次左連接,但目前爲止沒有任何運氣。

這是到目前爲止的代碼

SELECT * 
FROM users 
INNER JOIN `user_follows` ON users.instagram_id = user_follows.instagram_id 
WHERE user_follows.instagram_id != 'insta123' 

感謝您的幫助。

+0

請留下一些代碼,你到目前爲止。 – Skamielina

+0

你是指兩個用戶沒有跟隨或者兩個用戶都沒有跟隨另一個? – Orangepill

+0

我想你會想要一個'OUTER JOIN'。 – Jessica

回答

0

我建議你做一個子查詢來獲取你的關注者列表。然後使用LEFT JOIN並通過測試NULL來查找那些不是追隨者的人。

SELECT users.* from users 
left join 
(
    SELECT 
     users_follows.instagram_id_2 as 'instagram_id' 
    from users 
    inner join users_follows on users.instagram_id=users_follows.instagram_id_1 
    where users.instagram_id = 'insta123' 
) as followers on users.instagram_id = followers.instagram_id 
where followers.instagram_id is null 
and users.instagram_id != 'insta123' # you can't follow yourself 

我測試過它與您的結構副本,它工作正常。

相關問題