为此,我在以下链接上创建了一个小提琴:http ://www.sqlfiddle.com/#!2/7e007
我找不到SQL compact / CE,所以它在MySQL中。
桌子看起来像这样
Records Clients ID | NAME | AGE ID | NAME ------------------ ---------------- 1 | John | 20 1 | John 2 | Steven | 30 2 | Daniel 3 | Abraham | 30 3 | 4 | Donald | 25 5 | Lisa 6 | | 35 6 | Michael 7 | | 42 7 |
我想从两个表中进行选择,并且如果id在两个表中并且都具有名称,我希望将“ Clients”中的名称作为默认名称。如果“记录”中的名称为空,则使用客户端名称(如果有),并且“ Clients.Name”为空;否则,使用“客户端名称”。使用records.Name。
从上面的表中,我想这样:
ID | NAME | AGE ------------------ 1 | John | 20 2 | Daniel | 30 3 | Abraham | 30 4 | Donald | 25 5 | Lisa | 6 | Michael | 35 7 | | 42
如何在SQL Compact中做到这一点?
编辑:由于下面的出色答案,我设法提出了该查询,ALMOST可以工作:
SELECT t.id, t.name, t.age FROM ( ( SELECT r.id, CASE WHEN r.name = NULL THEN c.name ELSE r.name END as name, r.age FROM Records r LEFT JOIN Clients c ON c.id = r.id ) UNION ( SELECT c.id, c.name, null as age FROM Clients c where c.id NOT IN (select id from Records) ) ) as t ORDER BY t.id
这给了我这个输出:
ID | NAME | AGE ------------------ 1 | John | 20 2 | Daniel | 30 3 | Abraham | 30 4 | Donald | 25 5 | Lisa | 6 | | 35 7 | | 42
在这种情况下,“ Michael”(应该在#6上)丢失了。为什么?!
select r.id, IF(c.name != '',c.name,r.name) as name, r.age FROM Records r LEFT JOIN Clients c ON c.id = r.id GROUP BY c.id
使用上面的查询。
编辑:
SELECT t.id, t.name, t.age FROM ( ( SELECT r.id, CASE WHEN c.name <> '' THEN c.name ELSE r.name END as name, r.age FROM Records r LEFT JOIN Clients c ON c.id = r.id ) UNION ( SELECT c.id, c.name, null as age FROM Clients c where c.id NOT IN (select id from Records) ) ) as t ORDER BY t.id
使用此查询。