2015-04-02 43 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