使用 IN 时比较两个 SQL 查询
Comparing two SQL queries when using IN
我有两个 table,例如 Employee
和 Project
tables:
Employee (id, dept, joining_date)
Project (emp_id, project)
Project
具有来自 Employee
table 的外键。
我必须按照 joining_date
的顺序查询 project
和 dept
以及 return Employee
。对于以下查询的大数据集,哪个查询会更快?
select * from Employee where id in (select p.emp_id from Project p join Employee e on p.emp_id = e.id where p.project = 'project1' and e.dept = 'dept1') order by joining_date
select * from Employee where id in (select p.emp_id from Project p join Employee e on p.emp_id = e.id where p.project = 'project1' and e.dept = 'dept1') and dept = 'dept1' order by joining_date
或者有更好更简单的方法吗?
使用 IN()
表达式的外部查询完全没有必要。这将产生您需要的输出:
select e.*
from Project p
inner join Employee e on p.emp_id = e.id
where p.project = 'project1' and e.dept = 'dept1'
order by joining_date
我有两个 table,例如 Employee
和 Project
tables:
Employee (id, dept, joining_date)
Project (emp_id, project)
Project
具有来自 Employee
table 的外键。
我必须按照 joining_date
的顺序查询 project
和 dept
以及 return Employee
。对于以下查询的大数据集,哪个查询会更快?
select * from Employee where id in (select p.emp_id from Project p join Employee e on p.emp_id = e.id where p.project = 'project1' and e.dept = 'dept1') order by joining_date
select * from Employee where id in (select p.emp_id from Project p join Employee e on p.emp_id = e.id where p.project = 'project1' and e.dept = 'dept1') and dept = 'dept1' order by joining_date
或者有更好更简单的方法吗?
使用 IN()
表达式的外部查询完全没有必要。这将产生您需要的输出:
select e.*
from Project p
inner join Employee e on p.emp_id = e.id
where p.project = 'project1' and e.dept = 'dept1'
order by joining_date