2015-04-02 80 views
0

我想構建一個多對多的SQL查詢,然後將結果與其他表結合起來。與Join和Where子句的SQL多對多關係

我有5個表:文章,主題標籤,articles_hashtags(它映射hashtags.id和articles.id),用戶,作者。

如果我想查詢所有文章和獲得作者和用戶信息一起,我用這個查詢,它的工作原理:

SELECT articles.*, authors.name as authorName, users.name as userName 
    FROM articles 
    LEFT JOIN authors ON articles.authorId = authors.id 
    LEFT JOIN users ON articles.userId = users.id 

否則,如果我嘗試查詢具有一定的主題標籤的所有文章中,我使用這(如發現here):

SELECT articles.* 
    FROM articles, hashtags, articles_hashtags 
    WHERE hashtags.id = articles_hashtags.hashtagId 
    AND (hashtags.name IN ('prova')) 
    AND articles.id = articles_hashtags.articleId 
    GROUP BY articles.id 

但在這第二個我如何可以加入其它表(用戶和作者)的信息?

謝謝!

回答

1

可能是你正在尋找這個

我假設你正在尋找所有匹配的記錄

SELECT art.* 
    FROM articles art 
    INNER JOIN articles_hashtags arc_hs ON art.id = arc_hs.articleId 
    INNER JOIN hashtags hs on hs.id = arc_hs.hashtagId 
    INNER JOIN authors aut ON art.authorId = aut.id 
    INNER JOIN users u ON art.userId = u.id 
    WHERE hs.name IN ('prova') 
    GROUP BY art.id 

如果你想快速舉報通道的所有信息,而不管有其他表匹配的記錄,然後你可以使用left join

SELECT art.* 
    FROM articles art 
    LEFT JOIN articles_hashtags arc_hs ON art.id = arc_hs.articleId 
    LEFT JOIN hashtags hs on hs.id = arc_hs.hashtagId 
    LEFT JOIN authors aut ON art.authorId = aut.id 
    LEFT JOIN users u ON art.userId = u.id 
    WHERE hs.name IN ('prova') 
    GROUP BY art.id 

注:您正在使用CARTESIAN JOIN在您的第二個查詢中是very bad

+0

謝謝!它的工作 - 一些更正(我猜是因爲你不能嘗試查詢)。 這裏是正確的 'SELECT藝術。* 從文章的藝術 INNER JOIN articles_hashtags arc_hs ON art.id = arc_hs.articleId INNER JOIN主題標籤HS ON hs.id = arc_hs.hashtagId INNER JOIN作者AUT於藝術。 authorId = aut.id INNER JOIN用戶您在art.userId = u.id WHERE hs.name IN('prova') GROUP BY art.id'。如果您在回答中更正了這個問題,我會將問題標記爲「已解決」! – Camillo 2015-04-02 21:22:50

+0

@addis是的,我沒有嘗試。 – 2015-04-02 21:28:16

+0

在問題的第二個查詢中實際上沒有笛卡爾連接。這些連接在'WHERE'子句中,應該不鼓勵,但是所有的表都加入了。 – Allan 2015-04-02 21:30:32