我有一个请求,如果操作员输入什么,我将检索所有用户。但是如果运营商多次输入一些用户名,我只会退还用户的名字。名字是输入的,我想使用下面的子查询
我使用子查询(表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)
答案 0 :(得分: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.
案例3 当表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 </ p>