[英]MySQL join a different table based on field value
我有一個包含網站上發布的最后評論的表格,我想根據評論type
加入另一個表格。
Comments
表與此結構類似:
id | type | ressource_id |
---+------+--------------+
1 | 1 | 10 |
2 | 3 | 7 |
我想要做的是加入“新聞”表,如果類型type = 1
( on news.id = comments.ressource_id
),“tutorial”表,如果type type = 3
,等等。
我該怎么辦? 我嘗試過使用CASE
和UNION
不同查詢,但從未得到預期的結果。
謝謝。
嘗試使用left outer join
和匹配type
的on
子句:
select coalesce(n.id, t.id) id
, c.type
, c.resource_id
from comments c
left
outer
join news n
on n.id = comments.resource_id
and c.type = 1
left
outer
join tutorial t
on t.id = comments.resource_id
and c.type = 3
您可以使用聯合查詢執行此操作,假設您可以強制部分查詢生成類似的模式,方法如下:
select n.id as id, c.something as something
from news n, comments c
where n.type = 1
and n.id = c.resource_id
union all
select n.id as id, t.something as something
from news n, tutorial t
where n.type = 3
and n.id = t.resource_id
換句話說,第一個查詢只是連接news.type
表示comments
的行的news
和注釋,第二個查詢連接news.type
表示tutorials
的行的news
和教程。
然后聯盟將兩者合並為一個記錄集。
在這種情況下(以及許多其他情況)我會避開case
,因為它幾乎總是需要對數據進行每行修改,這很少會擴展。 運行兩個查詢並組合結果通常更有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.