2017-05-01 52 views
-2

我想從朋友所有職位,其中by_user(ID)與朋友(ID)匹配SQL |從朋友的帖子,檢查是否添加

當前表(僅將相關屬性包含):

用戶

+----+----------------+ 
| id | name   | 
+----+----------------+ 
| 1 | Blake   | 
| 2 | Jenn   | 
+----+----------------+ 

帖子

+----+----------------+----------------+ 
| id | by_user  | text   | 
+----+----------------+----------------+ 
| 1 | 1    | Post 1   | 
| 2 | 2    | Post 2   | 
+----+----------------+----------------+ 

朋友

+----+----------------+----------------+ 
| id | from   | to    | 
+----+----------------+----------------+ 
| 1 | 1    | 2    | 
| 2 | 2    | 1    | 
+----+----------------+----------------+ 

如果我朋友friends.to如果這樣的話顯示帖子所以basicly檢查。

回答

0

試試這個:

SELECT p.* 

FROM 
    posts AS p 

    INNER JOIN friends AS f 
     ON f.[to] = p.by_user 
     AND f.[from] = 1 -- Friends with user 1 
+0

我剛剛試過你的建議,但現在它給了我發佈和接收用戶的所有帖子。仍然感謝您的幫助。 –

+0

你想只收到他們收到的帖子嗎? – xcvd

+0

不,我想檢查用戶是否有其他用戶作爲朋友(從= 1到= 2)如果向他顯示用戶2的所有帖子 –

0

不知道這是正確的,但不妨一試。看起來你正在做一些家庭作業,你的老師很可能會看到這個答案。

select * from posts 
where by_user in(
    select distinct friend 
    from (
     select distinct "from" as friend 
     from friends 
     where "to" = :user_id 
     union 
     select distinct "to" as friend 
     from friends 
     where "from" = :user_id 
    ) as friends_sq 
) 
+0

在「:user_id union select distinct」處獲取#1064錯誤爲「從朋友處發過來的朋友」from「=:user_」 –