[英]Select non-null column in FULL OUTER JOIN
Consider the following tables: 请考虑以下表格:
Id | Name | Family
1 | name1 | family1
2 | name2 | family2
And: 和:
Id | Orderr | Countt
1 | order1 | 17
1 | order2 | 18
3 | order3 | 16
And the following query: 以下查询:
select table1.id,table1.name,table1.family,table2.orderr,table2.countt
from table1 FULL OUTER JOIN table2
on table1.id = table2.id
It returns: 它返回:
Id | Name | Family | Orderr | Countt
1 | name1 | family1 | order1 | 17
1 | name1 | family1 | order2 | 18
2 | name2 | family2 | NULL | NULL
NULL | NULL | NULL | order3 | 16
As you see in the last row it doesn't show the Id column. 正如您在最后一行中看到的那样,它不会显示Id列。 How can I change my query to return the Id column in the last row?
如何更改查询以返回最后一行中的Id列? I don't want to include
table2.id
in my select query because in this way I will have tow Id column. 我不想在我的选择查询中包含
table2.id
,因为这样我将有两列Id列。
Use COALESCE or ISNULL 使用COALESCE或ISNULL
COALESCE "returns the first non-null expression among its arguments," and ISNULL "replaces NULL with the specified replacement value."
COALESCE“在其参数中返回第一个非空表达式,”和ISNULL“用指定的替换值替换NULL。”
Analysis in details at http://sqlmag.com/t-sql/coalesce-vs-isnull 详细分析http://sqlmag.com/t-sql/coalesce-vs-isnull
SELECT ISNULL(table1.id, table2.id) AS id,
table1.name,table1.family,table2.orderr,table2.countt
FROM table1 FULL OUTER JOIN table2
ON table1.id = table2.id
OR 要么
SELECT COALESCE(table1.id, table2.id) AS id,
table1.name,table1.family,table2.orderr,table2.countt
FROM table1 FULL OUTER JOIN table2
ON table1.id = table2.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.