sql - 为什么以下查询有不同的输出?

标签 sql oracle11g sql-order-by

尽管 2*3-5 = 1 为什么这两个查询有不同的输出?

SELECT * FROM table ORDER BY 1 asc, column2 desc;

对比

SELECT * FROM table ORDER BY 2*3-5 asc, column2 desc;

最佳答案

按结果集中的第一列排序,然后按column2排序

SELECT * FROM table ORDER BY 1 asc, column2 desc;

按常量表达式和column2排序:

SELECT * FROM table ORDER BY 2*3-5 asc, column2 desc;
<=>
SELECT * FROM table ORDER BY column2 desc;

SqlFiddleDemo

ORDER BY { column-Name | ColumnPosition | Expression }

ColumnPosition

An integer that identifies the number of the column in the SelectItems in the underlying query of the SELECT statement. ColumnPosition must be greater than 0 and not greater than the number of columns in the result table. In other words, if you want to order by a column, that column must be specified in the SELECT list.

请记住,在某些 RDBMS 中不允许按常量排序,例如 SQL Server:

SELECT * 
FROM tab
ORDER BY 2*3-5 asc, column2 desc;
-- A constant expression was encountered in the ORDER BY list, position 1.

关于sql - 为什么以下查询有不同的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34470827/

相关文章:

sql - 如何从子查询(在 SQL Server 中)中选择多列,而主查询中的每条记录应有一条记录(选择前 1 条)?

sql - 在 Postgres 中插入自定义类型的数组

SQL升序排序时如何让空值排在最后

java - 从 Oracle DB 检查已提交的事务

c# - 如何通过两种不同类型的字段对 linq 查询结果进行排序

php - MySQL 查询加入主题的最后评论

mysql - 尝试加快大型表上的 mysql 查询速度

MySQL 创建 2013 年德国日期格式的表

sql - 如何处理表或 View 不存在异常?

java - 多线程与数据库(mysql 或 oracle)