![](/img/trans.png)
[英]How to return all the rows which has not match in join table and if it had match check the condition?
[英]SQL join return all rows (in either table or both) on condition
我有一個表,其中的列對內容進行了分類:
id lang string
1 EN text1_en
1 DE text1_de
1 FR text1_fr
2 EN text2_en
2 DE text2_de
3 DE text3_de
3 FR text3_fr
我想獲得這樣的結果:
id lang string id lang string id lang string
1 EN text1_en 1 DE text1_de 1 FR text1_fr
2 EN text2_en 2 DE text2_de NULL NULL NULL
NULL NULL NULL 3 DE text3_de 3 FR text3_fr
我最初嘗試加入:
select
c1.id,c1.lang,c1.string,
c2.id,c2.lang,c2.string,
c3.id,c3.lang,c3.string
from
mytable c1
left join mytable c2 on (c1.id=c2.id and c2.lang='DE')
left join mytable c3 on (c1.id=c3.id and c3.lang='FR')
where
c1.lang='EN'
order by c1.id
但是我只得到ID為1和2的結果。
如果將c1.lang='EN'
移到on
條件,我將獲得前3列的所有表行(不僅是lang='EN'
)
您可以在mysql以外的服務器中使用完全外部聯接。 對於大表,此查詢將花費一些時間。
select
c1.id,c1.lang,c1.string,
c2.id,c2.lang,c2.string,
c3.id,c3.lang,c3.string
from
mytable c1 left join mytable c2 on (c1.id=c2.id and c2.lang='DE')
left join mytable c3 on (c1.id=c3.id and c3.lang='FR')
where
c1.lang='EN'
UNION ALL
select
c1.id,c1.lang,c1.string,
c2.id,c2.lang,c2.string,
c3.id,c3.lang,c3.string
from
mytable c2 left join mytable c1 on (c2.id=c1.id and c1.lang='EN')
left join mytable c3 on (c2.id=c3.id and c3.lang='FR')
where
c2.lang='DE'
UNION ALL
select
c1.id,c1.lang,c1.string,
c2.id,c2.lang,c2.string,
c3.id,c3.lang,c3.string
from
mytable c3 left join mytable c1 on (c3.id=c1.id and c1.lang='EN')
left join mytable c2 on (c3.id=c2.id and c2.lang='DE')
where
c3.lang='FR'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.