考虑以下表格:
Id | Name | Family
1 | name1 | family1
2 | name2 | family2
和
Id | Orderr | Countt
1 | order1 | 17
1 | order2 | 18
3 | order3 | 16
以下查询:
select table1.id,table1.name,table1.family,table2.orderr,table2.countt
from table1 FULL OUTER JOIN table2
on table1.id = table2.id
它返回:
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
正如您在最后一行中看到的,它没有显示Id列。如何更改查询以返回最后一行中的Id列?我不想在我的选择查询中加入table2.id
,因为通过这种方式我会有两列Id列。
答案 0 :(得分:8)
使用COALESCE或ISNULL
COALESCE“返回第一个 其参数中的非null表达式,“和ISNULL”替换NULL 使用指定的替换值。“
详细分析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
答案 1 :(得分:3)