【问题标题】:Comparing two SQL queries when using IN使用 IN 时比较两个 SQL 查询
【发布时间】:2016-03-04 03:02:24
【问题描述】:

我有两个表,例如EmployeeProject 表:

Employee (id, dept, joining_date)
Project (emp_id, project)

Project 具有来自Employee 表的外键。 我必须查询projectdept 并按照joining_date 的顺序返回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

或者有没有更好更简单的方法?

【问题讨论】:

    标签: mysql sql sql-order-by where sql-in


    【解决方案1】:

    使用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
    

    【讨论】:

    • 感谢 Joel,但我无法弄清楚如何在 django 中进行此查询。我写的查询是 DJDT 打印的查询。
    猜你喜欢
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多