由于我在另一个帖子中提出错误并且它被正确回答,我开始一个新的线程..
我有两张桌子
Records
id | type
------------
1 | CD
2 | CD
Titles
record_id | name | language
-------------------------------
1 | Warning | 'en'
1 | Achtung | 'de'
2 | Ambulance | 'en'
(SQL Fiddle in link:http://www.sqlfiddle.com/#!2/403d4/1)
如果我要求使用'en'语言:
1 | Warning
2 | Ambulance
如果我要'de'我想要
1 | ACHTUNG
2 | NULL
如何编写SQL以获得此结果?
答案 0 :(得分:1)
http://www.sqlfiddle.com/#!2/403d4/89
SELECT rec.id, title.name
FROM Records rec
LEFT JOIN Titles title ON title.record_id = rec.id and title.language='de';
SELECT rec.id, title.name
FROM Records rec
LEFT JOIN Titles title ON title.record_id = rec.id and title.language='en';
ID NAME
1 ACHTUNG
2 (null)
ID NAME
1 Warning
2 Ambulance
答案 1 :(得分:0)
如果不存在相应的记录,则左外连接在第二个表中提供空值。
显然将'en'更改为'de'以查看其他结果:
Select
r.id,
t.name
From
Records r
Left Outer Join
Titles t
On r.id = t.record_id
Where
r.language = 'en'