我需要SQL查询的帮助。我有一个"主列表(X和Y类别)"。我必须将上面的列表与两个子列表表进行比较 - "列表X"和"列出Y"
表:
*MasterList*
ID Cat Status
101 X Ready
102 X Ready
103 Y Dispatched Y
104 X Dispatched Y
105 Y Dispatched
106 X Ready
107 X Dispatched Y
108 Y Ready Y
109 X Dispatched
110 Y Dispatched
111 X Ready Y
112 X Dispatched
113 X Dispatched Y
*ListX*
ID
101
102
106
109
112
*ListY*
ID
105
110
我正在尝试创建一个输出:
的查询输出
ID Cat Status
103 Y Dispatched
104 X Dispatched
107 X Dispatched
108 Y Ready
111 X Ready
113 X Dispatched
谢谢,
拉维。
答案 0 :(得分:0)
您可以通过多种方式完成此操作,例如:
select *
from master_list
where (cat = 'X' and id not in (select id from listx))
or (cat = 'Y' and id not in (select id from listy))
同时尝试not exists
和简单连接。
在Oracle和输出中测试数据:
create table master_list (id int, cat varchar2(1), status varchar2(15));
insert into master_list values (101, 'X', 'Ready');
insert into master_list values (102, 'X', 'Ready');
insert into master_list values (103, 'Y', 'Dispatched');
insert into master_list values (104, 'X', 'Dispatched');
insert into master_list values (105, 'Y', 'Dispatched');
insert into master_list values (106, 'X', 'Ready');
insert into master_list values (107, 'X', 'Dispatched');
insert into master_list values (108, 'Y', 'Ready');
insert into master_list values (109, 'X', 'Dispatched');
insert into master_list values (110, 'Y', 'Dispatched');
insert into master_list values (111, 'X', 'Ready');
insert into master_list values (112, 'X', 'Dispatched');
insert into master_list values (113, 'X', 'Dispatched');
create table listx as (select column_value id
from table(sys.odcinumberlist(101, 102, 106, 109, 112)));
create table listy as (select column_value id
from table(sys.odcinumberlist(105, 110)));
ID CAT STATUS
---- --- ---------------
103 Y Dispatched
104 X Dispatched
107 X Dispatched
108 Y Ready
111 X Ready
113 X Dispatched
答案 1 :(得分:0)
您可以在WHERE子句中使用OR:
SELECT ID, CAT, STATUS
FROM MASTERLIST M
WHERE (M.ID NOT IN (SELECT ID FROM LISTX) AND CAT = 'X')
OR (M.ID NOT IN (SELECT ID FROM LISTY) AND CAT = 'Y');
其他替代方法是将规则分成两个查询,然后与UNION ALL组合:
SELECT ID, CAT, STATUS
FROM MASTERLIST M
WHERE M.ID NOT IN (SELECT ID FROM LISTX) AND CAT = 'X'
UNION ALL
SELECT ID, CAT, STATUS
FROM MASTERLIST M
WHERE M.ID NOT IN (SELECT ID FROM LISTY) AND CAT = 'Y';
这两种技术都会产生相同的结果。实际上,一些优化器(如Oracle)会尝试将第一个解决方案实时转换为第二个解决方案。这被称为OR扩展。