SQL与Join和Where子句的多对多关系

时间:2015-04-02 15:07:41

标签: mysql sql

我尝试构建多对多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 个答案:

答案 0 :(得分: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