我已经查看了这个问题及其答案,但仍然不确定。我的简化架构是:
CREATE TABLE department(
ident text not null primary key,
name text not null,
building text not null
);
CREATE TABLE staff(
ident integer primary key autoincrement,
name text not null,
foreign key (dept) references department(ident)
);
我的查询正在尝试查找所有包含员工的构建:
select name, building
from department
where exists (
select 1
from staff
where dept == department.ident
)
order by name;
select distinct
department.name as name,
department.building as building
from department join staff
on department.ident = staff.dept
order by name;
在 Microsoft SQL Server 或 Oracle 数据库等优秀的 RDBMS 中,这些查询将产生完全相同的执行计划。
您必须记住,查询语言不是编程语言。 SQL 只允许您定义结果的形状,而不能定义检索信息的方式...
解析查询后,将其转换为关系代数公式,然后通过替换等数学规则进行简化,最后通过语义和统计规则进行优化,以重新排序操作顺序并选择适当的算法。
事实上,您编写的两个查询在数学上是严格等价的,并且必须产生相同的执行计划(例如,必须执行的最小操作序列才能给出结果)。
作为在 MS SQL Server 中的测试,这对上面的最终执行计划进行:
我认为你在 PostGreSQL...所以尝试使用 EXPLAIN 获取执行计划...