简体   繁体   中英

MySQL left join with extra clauses returns unmatched rows

I have a translations table

id | language | tr_text | orig_id

the orig_id serves to reference the original text eg

id | language | tr_text | orig_id
 1 | EN | Hello | 1
 2 | EN | Bye | 2
 3 |DE | Hallo | 1

Now I am trying to produce a query that gives me all of the original terms and all of the translated ones, with nulls where a translation has not be entered:

SELECT TransOrg.id, TransOrg.tr_text, TransOrg.tr_Language, TransLang.id, TransLang.tr_text, TransLang.tr_Language
FROM Translations AS TransOrg
LEFT JOIN Translations AS TransLang
ON TransOrg.id = TransLang.orig_id
AND TransOrg.Language = 'EN' AND TransLang.Language = 'DE'

This however returns what I want plus the DE translations:

1 | Hello | EN | 3 | Hallo | DE
2 | Bye | EN | null | null | null  
3 | Hallo | DE | null | null | null  < why is this here?! 

I thought the

AND TransOrg.Language = 'EN' 

condition would have stopped this

You should have TransOrg.Language = 'EN' in WHERE clause to prevent it from showing in the result set.

SELECT TransOrg.id, TransOrg.tr_text, TransOrg.tr_Language, TransLang.id,
  TransLang.tr_text, TransLang.tr_Language
 FROM Translations AS TransOrg
 LEFT JOIN Translations AS TransLang
 ON (TransOrg.id = TransLang.orig_id AND TransLang.Language = 'DE')
 WHERE TransOrg.Language = 'EN';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM