2017-06-18 111 views
0

我有兩個表,一個名爲Users,有id, name, last_name和一個名爲Messages的表具有id, user_id, message從關係表中的兩個不同表中獲取數據

我也有一個關係表,以跟隨其他用戶Follow用戶,在id, user_id, follower_user_id

我需要把所有從我的用戶的郵件的形式,可以說,用戶1,所有來自用戶1的消息追隨者。

我已經有一個查詢,但它沒有返回當前用戶的正確名稱。

我該如何做到這一點?下面是我最初的查詢,但它不會產生正確的結果。

SELECT DISTINCT Messages.content, Messages.user_id, Users.name 
    FROM Follow JOIN Users ON Users.id = Follow.follower_user_id 
    JOIN Messages ON Messages.user_id = Follow.follower_user_id 
    OR Messages.user_id = Follow.user_id WHERE Follow.user_id = 1 

樣本數據:

消息:

id | user_id | message 
1 |  1  | I am a message 
2 |  3  | Here is another message 
3 |  2  | Hello there 

用戶:

id | name | last_name 
1 | Test | Last 
2 | Test2 | Last2 
3 | Test3 | Last3 

如下:

id | user_id | follower_user_id 
1 |  1  | 2 
2 |  1  | 3 
3 |  3  | 1 
+0

編輯您的問題,並提供樣本數據和期望的結果。 –

回答

1

我希望是這樣的:

SELECT m.content, m.user_id, u.name 
FROM messages m JOIN 
    users u 
    ON m.user_id = u.id 
WHERE m.user_id = 1 OR 
     m.user_id IN (SELECT f.follower_user_id 
        FROM Follow f 
        WHERE f.user_id = 1 
        ); 

你應該儘量避免SELECT DISTINCT,除非它是必要的。

此外,您的問題措辭的方式,FOLLOW中的用戶列可能是錯誤的順序(也就是說,您可能希望f.follower_user_id = 1在子查詢中)。

相關問題