Order by 与union all优先级
时间: 2023-06-12 22:05:39 浏览: 130
union all与order by用法
5星 · 资源好评率100%
在 SQL 查询语句中,ORDER BY 和 UNION ALL 的优先级是不同的。具体来说,ORDER BY 的优先级比UNION ALL高。
这意味着,当查询中同时包含ORDER BY 和UNION ALL 时,ORDER BY 会先执行,然后才执行UNION ALL。因此,如果你想在UNION ALL之前对结果进行排序,则应该将ORDER BY 子句放在UNION ALL之前。
例如,以下查询首先按照salary字段对employee表进行排序,然后再将结果与department表合并:
```
SELECT employee.name, employee.salary, department.department_name
FROM employee
INNER JOIN department ON employee.department_id = department.department_id
ORDER BY employee.salary
UNION ALL
SELECT employee.name, employee.salary, department.department_name
FROM employee
INNER JOIN department ON employee.department_id = department.department_id
ORDER BY department.department_name;
```
在这个查询中,首先对employee表按照salary字段进行排序,然后使用UNION ALL将结果与department表合并。如果我们想按照department_name字段对结果进行排序,则需要在UNION ALL之前加上ORDER BY子句:
```
SELECT employee.name, employee.salary, department.department_name
FROM employee
INNER JOIN department ON employee.department_id = department.department_id
ORDER BY employee.salary
UNION ALL
SELECT employee.name, employee.salary, department.department_name
FROM employee
INNER JOIN department ON employee.department_id = department.department_id
ORDER BY department.department_name
ORDER BY department.department_name;
```
在这个查询中,首先对employee表按照salary字段进行排序,然后使用UNION ALL将结果与department表合并,最后再按照department_name字段进行排序。
阅读全文