在Oracle中查找数据子集

时间:2017-06-30 06:25:10

标签: sql oracle

我在emp1中有一些记录:

SELECT distinct 
substrb(emp.employee_NAME,1,50) employee_NAME 
FROM employee emp , employee_sites sites , (SELECT DISTINCT employee_id ,
emp_site_number
FROM abc
) abc
where emp.employee_id = sites.employee_id
and abc.employee_id=emp.employee_id
and abc.emp_site_number = sites.emp_site_number ;

以及emp中的一些记录:

SELECT  distinct emp.employee_NAME employee_NAME 
FROM employee emp
WHERE 1=1 and EXISTS
(SELECT 1 FROM employee_ACCOUNTS acc WHERE acc.employee_id = emp.employee_id
) 

empc的行数:205001 empc的行数:18003

我想知道emp是否具有emp1的所有记录,换句话说,如果emp是emp1的超集。我试过这个:

select count(*)  from (SELECT  distinct emp.employee_NAME employee_NAME 
FROM employee emp
WHERE 1=1 and EXISTS
(SELECT 1 FROM employee_ACCOUNTS acc WHERE acc.employee_id = emp.employee_id
) ) emp ,
(SELECT distinct 
substrb(emp.employee_NAME,1,50) employee_NAME 
FROM employee emp , employee_sites sites , (SELECT DISTINCT employee_id ,
emp_site_number
FROM abc
) abc
where emp.employee_id = sites.employee_id
and abc.employee_id=emp.employee_id
and abc.emp_site_number = sites.emp_site_number)  emp1
where emp.employee_NAME = emp1.employee_NAME ;

以上查询的Rowcount:12360。 所以我得出结论,emp不是emp1的超集

有人请让我知道我做的很好或需要一些修改。 如果你知道一些更好的方法,也请分享。

由于

1 个答案:

答案 0 :(得分:2)

你可以避免相关的子查询,只需做一个简单的设置MINUS操作:

select employee_name -- or whatever makes the employee the same in 2 tables
from emp1 -- the table which may have rows not in the other table

MINUS

select employee_name
from emp2 -- the table which you think may be missing some rows

您也可以使用左连接:

select emp2.employee_name from emp2
left join emp1 on emp2.employee_name = emp1.employee_name
where emp1.employee_name is null

性能取决于索引,数据量等因素。检查查询计划和基准测试将使您更好地了解哪个是更好的选择。