我在标准的HR Oracle数据库上练习,我对使用集合运算符INTERSECT有疑问。我有这些情况:
SELECT employee_id, job_id, department_id
FROM employees
NATURAL JOIN job_history;
SELECT employee_id, job_id, department_id
FROM employees
INTERSECT
SELECT employee_id, job_id, department_id
FROM job_history;
两个陈述都有相同的结果。有任何性能差异???感谢。
答案 0 :(得分:2)
Natural join
与intersect
完全不同。
在两个查询中,您似乎只在两个表中选择具有相同名称的列。 (否则,将natural join
与intersect
进行比较从一开始就没有意义。)这是您在问题陈述中应该明确的内容。
然后:如果同一employee/job/department
job_history
表中有多行,则自然连接中将存在相同数量的行(假设employee_id
是PK { {1}})。另一方面,employees
删除重复项。所以,即使你设置它的方式,这两个操作也不一样 - 除非你愿意在加入之前(或之后)加intersect
,这会增加更多的开销。
如果您需要SELECT DISTINCT
,请使用intersect
运算符,它的用途是什么。每当你认为你找到另一种方法来获得相同的结果时,通常是因为你忽略了某些东西(比如在这种情况下处理重复的东西)。
答案 1 :(得分:0)
如果任何列值为NULL,SQLite的Natural Join将从两个表中排除相同的匹配。
鉴于表:
+--------------------------------------+ | employees | +--------------------------------------+ | employee_id | job_id | department_id | +-------------+--------+---------------+ | 1 | NULL | 10 | +-------------+--------+---------------+ | 2 | EMPTY | 20 | +-------------+--------+---------------+ | 3 | "id3" | 30 | +-------------+--------+---------------+
和
+--------------------------------------+ | job_history | +--------------------------------------+ | employee_id | job_id | department_id | +-------------+--------+---------------+ | 1 | NULL | 10 | +-------------+--------+---------------+ | 2 | EMPTY | 20 | +-------------+--------+---------------+ | 3 | "id3" | 30 | +-------------+--------+---------------+ | 4 | "id4" | 40 | +-------------+--------+---------------+
select * from employees natural join job_history
结果:
+-------------+--------+---------------+ | 2 | EMPTY | 20 | +-------------+--------+---------------+ | 3 | "id3" | 30 | +-------------+--------+---------------+
select * from employees intersect select * from job_history
结果:
+-------------+--------+---------------+ | 1 | NULL | 10 | +-------------+--------+---------------+ | 2 | EMPTY | 20 | +-------------+--------+---------------+ | 3 | "id3" | 30 | +-------------+--------+---------------+