我有一个名为 test_table_1 的表和一个名为 temp_test_view_1 的视图。
目标是为test_table_1中的每个ID查找NEW_CATEGORY_ID。在视图 temp_test_view_1
中,NEW_CATEGORY_ID与ID之间的关系我为此目的使用左联接,基表为test_table_1。
我认为左联接返回一些意外结果。
这是表 test_table_1 中包含的所有数据:
select * from test_table_1:
id name
1 'a'
null 'd'
3 'd'
2 'c'
2 'b'
这是视图脚本:
create view temp_test_view_1 as
select
id,
id_description,
case when id_category = 'phone_id' then 'phone' else 'other' end as new_id_category
from (
select
1 as id,
'first id' as id_description,
null as id_category
from dummy
union all
select
2 as id,
'second id' as id_description,
'phone_id' as id_category
from dummy
) x
;
这是我用来将视图左连接到表,然后投影结果以查看test_table_1中每个ID对应的new_id_category的查询:
select
t1.id,
t1.name,
t2.id,
t2.id_description,
t2.new_id_category
from test_table_1 t1
left join temp_test_view_1 t2 on t1.id = t2.id
输出为:
id name,id id_description new_id_category
null 'd' null null, 'other'
1 'a' 1 'first id' 'other'
2 'b' 2 'second id' 'phone'
2 'c' 2 'second id' 'phone'
3 'd' null null 'other'
所需的输出:
id name,id id_description new_id_category
null 'd' null null, null
1 'a' 1 'first id' 'other'
2 'b' 2 'second id' 'phone'
2 'c' 2 'second id' 'phone'
3 'd' null null null
有人可以解释查询产生的结果是否正确,为什么?我希望这个左联接在从视图中检索的列上返回null,正如您从我期望的结果中可以看到的那样。
我没有在其他供应商提供的数据库系统中测试查询。
编辑: 我在sqlfiddle MS SQL上测试了它,并产生了所需的输出。链接在这里: sqlfiddle.com /#!18 / 1c788 / 2
如果有人需要代码本身来重现MS SQL中的结果,(尽管他将无法重现结果,而是获得所需的结果):
create view temp_test_view_1 as
select
id,
id_description,
case when id_category = 'phone_id' then 'phone' else 'other' end as new_id_category
from (
select
1 as id,
'first id' as id_description,
null as id_category
union all
select
2 as id,
'second id' as id_description,
'phone_id' as id_category
) x
;
select *
into test_table_1
from (
select
1 as id,
'a' as name
union all
select
2 as id,
'b' as name
union all
select
2 as id,
'c' as name
union all
select
3 as id,
'd' as name
union all
select
null as id,
'd' as name
) x;
select
t1.id,
t1.name,
t2.id,
t2.id_description,
t2.new_id_category
from test_table_1 t1
left join temp_test_view_1 t2 on t1.id = t2.id