如何在两个字段上加入,其中一个字段可以为null

时间:2017-04-06 15:54:55

标签: sql-server

这个查询可能看起来很基本,但我处于相当基本的水平。

所以这是我的数据 - 对格式化感到抱歉,我尝试过关注帮助,但表格格式显然不适用于我(有人可以建议吗?)

表1

ID |Country
---| ------- 
1  | UK
1  | IE 
1  | US   
2  | UK 
2  | FR

表2

ID |Country
---| ------- 
1  | UK
1  | IE 
2  | UK 

我想要的结果就是这个

Table 1-----  | ----Table 2

ID |Country   |-----ID |Country
---| -------  |--------|--------
1  | UK       | 1      | UK
1  | IE       | 1      | IE
1  | US       | 1      | NULL
2  | UK       | 2      | UK
2  | FR       | 2      | NULL

但更具体地说,我想识别NULL,以便我得到这个结果

Table 1-----  | ----Table 2

ID |Country   |-----ID |Country
---| -------  |--------|--------
1  | US       | 1      | NULL
2  | FR       | 2      | NULL

到目前为止,我使用的代码是:

select *
from table1 t1
left outer join table2 t2 on t1.id = t2.id and t1.country = t2.country
where t1.id is not null
and t2.country is null

2 个答案:

答案 0 :(得分:1)

试试这个

select t1.id, t1.country, isnull(t2.id, t1.id) AS T2_ID, t2.country
from table1 t1
left outer join table2 t2 on t1.id = t2.upc and t1.country = t2.country

如果您只想在t2中显示空值,可以添加

where t2.id is null

但是如果你想要显示所有记录,只需保留它没有WHERE条件

答案 1 :(得分:0)

你很接近,你只需要使用isnull()coalesce()

select 
    t1.id
  , t1.country
  , t2_Id = isnull(t2.id,t1.id)
  , t2_country = t2.country 
from table1 t1
left outer join table2 t2 on t1.id = t2.id and t1.country = t2.country
where t1.id is not null
  --and t2.country is null

rextester 演示http://rextester.com/XCNH52338

返回:

+----+---------+-------+------------+
| id | country | t2_Id | t2_country |
+----+---------+-------+------------+
|  1 | UK      |     1 | UK         |
|  1 | IE      |     1 | IE         |
|  1 | US      |     1 | NULL       |
|  2 | UK      |     2 | UK         |
|  2 | FR      |     2 | NULL       |
+----+---------+-------+------------+

使用t2.country is null

的附加过滤器

返回:

+----+---------+-------+------------+
| id | country | t2_Id | t2_country |
+----+---------+-------+------------+
|  1 | US      |     1 | NULL       |
|  2 | FR      |     2 | NULL       |
+----+---------+-------+------------+

两者之间的主要区别在于coalesce()可以支持2个以上的参数,并选择第一个不是null的参数。两者之间的差异更大answered here.

coalesce()是标准的ANSI sql,因此它在大多数RDBMS中都可用。 isnull()特定于sql server。

参考: