0

我有一个请求,如果操作员没有输入任何内容,我将检索所有用户。但是如果操作员多个输入一些用户名,我只检索输入了用户名的用户,我正在尝试使用如下子查询

我使用 subquery(table b) 作为 IN 条件从表 a 中获取用户信息,并且运行良好。

SELECT * FROM a WHERE UserName IN (SELECT UserName FROM b)

但是,如果表 b 什么都没有,我需要从 a 中选择所有用户,我不知道该怎么做。在我只能为一个用户执行此操作之前,如果 typeInUserName = NULL,WHERE UserName = UserName 将为我收回所有用户。

SELECT * FROM a WHERE UserName = NVL(typeInUserName,UserName)
4

1 回答 1

0
create table a (username varchar2(20));

insert into a values('gaurav');
insert into a values('rahul');
insert into a values('rohan');
insert into a values('niharika');

create table b (username varchar2(20));

 insert into b values('gaurav');
 insert into b values('rahul');

案例1:当表B中没有记录时

Delete from  b;

WITH cnt_b as 
(
 select count(*) cnt from b
)
select a.username from a ,cnt_b where  1= CASE WHEN cnt_b.cnt=0 THEN 1 ELSE 0 END
UNION 
select a.username from a,cnt_b,b where a.username =b.username and cnt_b.cnt>0;

USERNAME            

gaurav              
niharika            
rahul               
rohan               

4 rows selected.

案例2当表B中有两条匹配记录时

 insert into b values('gaurav');
 insert into b values('rahul');

WITH cnt_b as 
(
 select count(*) cnt from b
)
select a.username from a ,cnt_b where  1= CASE WHEN cnt_b.cnt=0 THEN 1 ELSE 0 END
UNION 
select a.username from a,cnt_b,b where a.username =b.username and cnt_b.cnt>0;


USERNAME            
--------------------
gaurav              
rahul               

2 rows selected.

Case3当表 B 中有记录,但没有匹配的记录时。

delete from  b

insert into b values('rajat');
insert into b values('garima');

with cnt_b as 
(
 select count(*) cnt from b
)
select a.username from a ,cnt_b where  1= CASE WHEN cnt_b.cnt=0 THEN 1 ELSE 0 END
UNION 
select a.username from a,cnt_b,b where a.username =b.username and cnt_b.cnt>0

no rows selected.

干杯 GS

于 2012-07-23T20:13:56.517 回答