簡體   English   中英

mysql查詢中的多個聯接

[英]multiple joins in mysql query

我正在創建一個模擬Twitter網站,對於主供稿,我正在嘗試查詢數據庫中的所有帖子,並從用戶那里重新發布帖子,指出有人遵循$ user_id是當前登錄的人。但是它僅顯示我運行查詢時重新發布的帖子。 誰能給我有關如何解決此問題的建議?

$query_feed = "SELECT posts.post, posts.date, users.handle, posts.id, posts.image,        users.profile_pic, repost.post_id, repost.user_id
                FROM posts
                JOIN users ON posts.author_id = users.id
                JOIN following ON " . $user_id . " = following.follower_id
                JOIN repost ON posts.id = repost.post_id
                WHERE (posts.author_id = following.followee_id) OR (repost.user_id = following.followee_id)
                ORDER BY posts.id desc";

這是因為您在重新發布時有一個“內部聯接”(“ join”實際上是“內部聯接”的簡稱):

JOIN repost ON posts.id = repost.post_id

這樣做意味着,只有在repost有匹配的記錄時,您才會在結果集中獲得一條記錄。

而是嘗試“外部聯接”或“左聯接”

LEFT JOIN repost ON posts.id = repost.post_id

這意味着即使repost沒有任何內容,您也可以獲得記錄

我已經稍微簡化了您的表(刪除了列),但是在此處使用SqlFiddle證明了這一點: http ://www.sqlfiddle.com/#!2/ee33a

如果您不希望repost表消除結果集中的記錄,則需要使用外部聯接。

另外, following表的join條件位於where子句中,而where子句包含您的join條件。 此外,由於您的following join條件在repost引用了一個字段,因此加入順序不正確。

$query_feed = "SELECT posts.post, posts.date, users.handle, posts.id, posts.image,        users.profile_pic, repost.post_id, repost.user_id
                FROM posts
                JOIN users ON posts.author_id = users.id
                LEFT JOIN repost ON posts.id = repost.post_id
                JOIN following ON (posts.author_id = following.followee_id) OR (repost.user_id = following.followee_id)
                WHERE " . $user_id . " = following.follower_id
                ORDER BY posts.id desc";

我不確定MySQL如何精確地處理事情,但是當您進行following表連接時,您可能仍然會從LEFT JOIN獲得NULL的問題。 我會在查詢分析器中運行查詢以確定您是否獲得了預期的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM