首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

子查询

Posted on 2007-04-22 22:02  小城  阅读(170)  评论(0)    收藏  举报
create table tabA
(
varchar(10),
int not null
)

create table tabB
(
int not null,
varchar(10not 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