[英]SQL many-to-many relationship with Join and Where clause
我正在尝试建立多对多SQL查询,然后将结果与其他表结合在一起。
我有5个表格:articles,hashtags,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
否则,如果我尝试查询带有特定主题标签的所有文章,则会使用此标签(如此处所示 ):
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
但是在第二篇文章中,我如何才能将其他表(用户和作者)中的信息结合起来?
谢谢!
可能是您在寻找这个
我假设您正在寻找所有匹配的记录
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.