不存在和减去

use*_*054 -3 sql plsql oracle10g oracle11g plsqldeveloper

任何人都可以告诉我SQL中NOT EXIST和MINUS运算符之间的差异吗?我何时可以使用?哪一个可以提供更好的性能?

Tho*_*ner 5

MINUS只有当它与同一列有关时才使用.这可能导致非常易读的查询:

select dept_id from employees where salary > 1000
minus
select dept_id from employees where salary < 500;
Run Code Online (Sandbox Code Playgroud)

NOT EXISTS更灵活,但对于可以使用查询轻松表达MINUS的查询可能会变得不那么可读:

select dept_id from departments d
where exists
          (select * from employees e where e.dept_id = d.dept_id and e.salary > 1000)
and not exists 
          (select * from employees e where e.dept_id = d.dept_id and e.salary < 500);
Run Code Online (Sandbox Code Playgroud)

至于速度,应该没有太大差别.别担心.将您的查询编写为尽可能可读,并且只考虑在遇到性能问题时重新编写它们.(但这些通常更多地是关于适当的索引,而不是关于如何编写查询的常见问题.Oracle善于理解查询,甚至可能在执行查询之前在内部重新编写MINUS查询,NOT EXISTS反之亦然.)