简体   繁体   English

子查询顺序

[英]Order by subquery

I have the following oracle SQL code, but I can't understand what is the purpose of ordering by a subquery. 我有以下oracle SQL代码,但无法理解子查询进行排序的目的。 Anyone can explain it clearly to me ? 有人可以向我清楚解释吗?

SELECT employee_id, last_name
  FROM employees e
 ORDER BY (
            SELECT department_name
            FROM departments d
            WHERE e.department_id = d.department_id
           );

The ordering is done by results from other table. 排序由其他表的结果完成。 In this case the query returns only results from employees table, but the ordering is done by department_name , which is stored in departments table. 在这种情况下,查询仅返回employees表中的结果,但是排序是通过department_name ,存储在departments表中。

You could achieve identical result by using join, selecting only values from employees table, and ordering by department_name from departments table: 通过使用联接,仅从employees表中选择值以及从departments表中按department_name排序,您可以实现相同的结果:

SELECT e.employee_id, e.last_name
FROM employees e INNER JOIN departments d
    ON e.department_id = d.department_id
ORDER BY d.department_name

This query is valid if employee must always have a department. 如果员工必须始终拥有部门,则此查询有效。 If there can be employees without departments then you should use LEFT join instead. 如果可以有没有部门的员工,则应改用LEFT

The clear intention of that query is employee_id and last_name from employees should be order by department_name from departments. 该查询的明确意图是employee_id,员工的last_name应该按部门的department_name排序。

Okay, you don't subquery then go for join 好吧,您不进行子查询然后加入

select e.employee_id,e.last_name from employees e join departments d on
e.department_id = d.department_id order by d.department_name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM