今天遇到的一个大坑,话不多少,看sql和下边的查询结果:
--问题:恰好把buildingid is null的记录给过滤掉
create table tommyduan_gridcell_group_all_test(gridid nvarchar(32),buildingid nvarchar(32),floor nvarchar(32));
insert into tommyduan_gridcell_group_all_test(gridid,buildingid,floor)values('g1',null,1);
insert into tommyduan_gridcell_group_all_test(gridid,buildingid,floor)values('g2','b1',1);
insert into tommyduan_gridcell_group_all_test(gridid,buildingid,floor)values('g2','b2',1);
insert into tommyduan_gridcell_group_all_test(gridid,buildingid,floor)values('g3','b2',1);
insert into tommyduan_gridcell_group_all_test(gridid,buildingid,floor)values('g3','b2',2);
insert into tommyduan_gridcell_group_all_test(gridid,buildingid,floor)values('g3','b2',4); create table tommyduan_fingerlib(gridid nvarchar(32),buildingid nvarchar(32),floor nvarchar(32));
insert into tommyduan_fingerlib(gridid,buildingid,floor)values('g1',null,1);
insert into tommyduan_fingerlib(gridid,buildingid,floor)values('g2','b1',1);
insert into tommyduan_fingerlib(gridid,buildingid,floor)values('g2','b2',1);
insert into tommyduan_fingerlib(gridid,buildingid,floor)values('g3','b2',1);
insert into tommyduan_fingerlib(gridid,buildingid,floor)values('g3','b2',2);
insert into tommyduan_fingerlib(gridid,buildingid,floor)values('g3','b2',4); select * from tommyduan_gridcell_group_all_test t10
inner join tommyduan_fingerlib t11
on t10.gridid=t11.gridid and t10.buildingid=t11.buildingid and t10.floor=t11.floor
查询结果:
解决方案:
select * from
(
select gridid,buildingid,floor,gridid+(case when buildingid is null then 'd_null' else buildingid end)+floor as tkey
from tommyduan_gridcell_group_all_test
) t10
inner join
(
select gridid,buildingid,floor,gridid+(case when buildingid is null then 'd_null' else buildingid end)+floor as tkey
from tommyduan_fingerlib
) t11
on t10.tkey=t11.tkey
查询结果:
left outer join时的查询结果是:
select * from tommyduan_gridcell_group_all_test t10
left outer join tommyduan_fingerlib t11
on t10.gridid=t11.gridid and t10.buildingid=t11.buildingid and t10.floor=t11.floor