我要问的是这个查询 -
select * from emp order by sal + 2000;
提供与此查询完全相同的结果 -
select * from emp order by sal;
那么计算方面有什么不同?
order by sal + 2000
是什么意思?
这对结果有何影响?
答案 0 :(得分:1)
从您的查询中考虑以下结果集,按薪水按升序排序(默认情况下):
select name, salary from emp order by sal;
+------+--------+
| name | salary |
+------+--------+
| John | 10000 |
| Mike | 15000 |
| Joe | 30000 |
+------+--------+
以下是使用ORDER BY sal + 2000
的结果集:
select name, salary, (salary+2000) as new_salary from emp order by new_salary;
+------+--------+------------+
| name | salary | new_salary |
+------+--------+------------+
| John | 10000 | 12000 |
| Mike | 15000 | 17000 |
| Joe | 30000 | 32000 |
+------+--------+------------+
将2000添加到工资中并不会改变你获得的顺序。
答案 1 :(得分:1)
如果SAL存储为字符串,那些查询不会给出相同的结果。
create table emp as
select '90000' sal from dual union all
select '100000' sal from dual union all
select '110000' sal from dual;
select * from emp order by sal;
SAL
---
100000
110000
90000
select * from emp order by sal + 2000;
SAL
---
90000
100000
110000
我希望这是不寻常的,但字符串类型的数据模型太常见了。
使用表达式可能会更改执行计划并避免使用索引。
create table emp2(id number, sal number not null);
select 1 id, 90000 sal from dual union all
select 2 id, 100000 sal from dual union all
select 3 id, 110000 sal from dual;
create index emp2_idx on emp2(sal);
explain plan for select * from emp2 order by sal;
select * from table(dbms_xplan.display(format => 'basic'));
Plan hash value: 1831800775
------------------------------------------------
| Id | Operation | Name |
------------------------------------------------
| 0 | SELECT STATEMENT | |
| 1 | TABLE ACCESS BY INDEX ROWID| EMP2 |
| 2 | INDEX FULL SCAN | EMP2_IDX |
------------------------------------------------
explain plan for select * from emp2 order by sal + 2000;
select * from table(dbms_xplan.display(format => 'basic'));
Plan hash value: 2441141433
-----------------------------------
| Id | Operation | Name |
-----------------------------------
| 0 | SELECT STATEMENT | |
| 1 | SORT ORDER BY | |
| 2 | TABLE ACCESS FULL| EMP2 |
-----------------------------------
通常有其他更好的方法来避免索引,但有些人会使用这种方法。
答案 2 :(得分:0)
order by sal + 2000
以上行可能没用,因为它可以执行以下两种操作之一:
答案 3 :(得分:0)
Order by子句用于根据您指定的列对结果进行排序 在您的情况下,默认情况下,您的结果将由Sal命令为ASC(升序)订单
按顺序执行计算对结果本身没有影响。