create table tabA
(
a varchar(10),
b int not null
)
create table tabB
(
c int not null,
d varchar(10) not null
)
insert into tabA values('aa',1)
insert into tabA values('bb',2)
insert into tabA values('cc',3)
insert into tabB values(1,'ee')
insert into tabB values(2,'ff')
insert into tabB values(5,'gg')
--有以上结构的两个表:
--现要,如果tabB表中有数据则显示tabA表字段b与tabB表中字段c匹配的tabA表记录,
--如果tabB表没有数据则显示tabA表全部记录
--解决方案:
select * from tabA where (b in (select c from tabB)
or not exists(select 1 from tabB))
/**//*
当tabB有记录时条件(true or false)或(false or false),可见只会找出匹配
当tabB有记录时条件(true or true)或(false or true),可见恒为true tabB表的记录永远显示
*/
drop table tabA
drop table tabB
(
a varchar(10),
b int not null
)
create table tabB
(
c int not null,
d varchar(10) not null
)
insert into tabA values('aa',1)
insert into tabA values('bb',2)
insert into tabA values('cc',3)
insert into tabB values(1,'ee')
insert into tabB values(2,'ff')
insert into tabB values(5,'gg')
--有以上结构的两个表:
--现要,如果tabB表中有数据则显示tabA表字段b与tabB表中字段c匹配的tabA表记录,
--如果tabB表没有数据则显示tabA表全部记录
--解决方案:
select * from tabA where (b in (select c from tabB)
or not exists(select 1 from tabB))
/**//*
当tabB有记录时条件(true or false)或(false or false),可见只会找出匹配
当tabB有记录时条件(true or true)或(false or true),可见恒为true tabB表的记录永远显示
*/
drop table tabA
drop table tabB
浙公网安备 33010602011771号