如果存在值,请从其他表中选择

时间:2014-01-23 10:29:43

标签: sql sql-server-ce

我在这个链接上创建了一个小提琴: 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”中的名称作为默认名称。如果Records中的名称为空,请使用客户端名称(如果有),如果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
在这种情况下,“迈克尔”(应该在#6上)缺失。为什么呢?!

4 个答案:

答案 0 :(得分:0)

使用COALECSE获取第一个非空值:

select id, coalesce(clients.name, records.name) as correct_name, records.age
from records
join clients using (id);

编辑:如果现有名称不存储为''而不是NULL,请使用:

select id, case when clients.name = '' then records.name else clients.name end as correct_name, records.age
from records
join clients using (id);

当然你也可以通过询问

对''和NULL做出反应
when clients.name = '' or clients.name is null then

请参阅http://www.sqlfiddle.com/#!2/7e007/36

答案 1 :(得分:0)

    select case when a.id <> '' then a.id else b.id end as id ,
case when a.name <> '' then a.name else b.name end as name,a.age
 from records a 
full outer join clients b on a.Id = b.id
order by a.id

答案 2 :(得分:0)

请尝试,希望这会有用..

select c.id,
IF(NAME='',(select name from Records where id = c.id),'')
If(NAME=NULL,(select name from Records where id = c.id),NULL)
Else c.NAME
from client c;

欢呼声!!!

答案 3 :(得分:0)

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 

使用此查询。