[英]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.