来自 Oracle 文档
http://docs.oracle.com/cd/E11882_01/server.112/e26088/queries004.htm#SQLRF52341
“MINUS 示例以下语句将结果与 MINUS 运算符组合在一起,该运算符仅返回第一个查询而不是第二个查询返回的唯一行:”
SELECT product_id FROM inventories
MINUS
SELECT product_id FROM order_items;
你的要求有点复杂。我假设 cols_a、cols_b、cols_c、cols_d 的组合对于表 A 中的记录是唯一的。在这种情况下,以下代码应该可以解决您的问题:
create table A (
cols_date DATE,
cols_a NUMBER,
cols_b NUMBER,
cols_c NUMBER,
cols_d NUMBER
);
create table B (
cols_a NUMBER,
cols_b NUMBER,
cols_c NUMBER,
cols_d NUMBER
);
insert into A (cols_date, cols_a, cols_b, cols_c, cols_d) values (sysdate, 1, 1, 1, 1);
insert into A (cols_date, cols_a, cols_b, cols_c, cols_d) values (sysdate, 2, 2, 2, 2);
insert into B (cols_a, cols_b, cols_c, cols_d) values (2, 2, 2, 2);
insert into B (cols_a, cols_b, cols_c, cols_d) values (3, 3, 3, 3);
commit;
select a.cols_date, a.cols_a, a.cols_b, a.cols_c, a.cols_d from (
select cols_a, cols_b, cols_c, cols_d
from A
minus
select cols_a, cols_b, cols_c, cols_d
from b
) ma, a
where 1=1
and ma.cols_a = a.cols_a
and ma.cols_b = a.cols_b
and ma.cols_c = a.cols_c
and ma.cols_d = a.cols_d;
结果是
COLS_DATE COLS_A COLS_B COLS_C COLS_D
--------------------- ---------- ---------- ---------- ----------
01.07.2013 13:20:02 1 1 1 1
NOT EXISTS 也可以解决问题。该语句的执行计划比 MINUS 版本更好。
感谢 David Aldridge 提供的解决方案。
select
cols_date,
cols_a, cols_b, cols_c, cols_d
from
a
where
not exists (
select 1
from b
where 1=1
and b.cols_a = a.cols_a
and b.cols_b = a.cols_b
and b.cols_c = a.cols_c
and b.cols_d = a.cols_d
);