1这个订单是1?

Mas*_*ter 13 mysql sql-order-by

我在MySQL中有一个问题,做得对.但书籍代码略有不同.

书:

use tennis;
select playerno, datediff(coalesce(end_date, current_date), 
begin_date) as Difference, position
from committee_members
where datediff(coalesce(end_date, current_date), begin_date) > 500
order by 1;
Run Code Online (Sandbox Code Playgroud)

1这个订单是什么?

我的代码也有效,几乎相同,除了:

select playerno, datediff(coalesce(end_date, current_date) AS Data,
order by Data;
Run Code Online (Sandbox Code Playgroud)

Jer*_*fin 27

order by 1表示"我选择的第一个字段的顺序" - 即,在这种情况下,相同order by playerno,因为playerno是列表中的第一个字段.

编辑:快速查看SQL-92标准的草稿确认了这一点:

10)If ORDER BY is specified, then each <sort specification> in the
        <order by clause> shall identify a column of T.

        Case:

        a) If a <sort specification> contains a <column name>, then T
          shall contain exactly one column with that <column name> and
          the <sort specification> identifies that column.

        b) If a <sort specification> contains an <unsigned integer>,
          then the <unsigned integer> shall be greater than 0 and not
          greater than the degree of T. The <sort specification> iden-
          tifies the column of T with the ordinal position specified by
          the <unsigned integer>.
Run Code Online (Sandbox Code Playgroud)

在这种情况下,b是一个似乎适用的.虽然我确信这个草案和标准的最终文本之间至少有一些变化(更不用说标准的一个版本和另一个版本之间),但这个基础的东西似乎不太可能发生变化(可能永远).

  • 让我们用 MySQL 自己的文档来支持它,而不是遵从标准:https://dev.mysql.com/doc/refman/5.7/en/select.html 关键字:'order by 2' (2认同)

sac*_*een 5

这被称为"ORDER BY序数",基本上按该位置的列顺序排列.按1排序表示第一个选定列的顺序.在你的例子中,它将等同于说ORDER BY playerno

我不建议这样做,因为它不清楚它引用的是什么列,如果列顺序改变,查询将返回不同的结果.

更多资源:

快速提示:按1说明排序

踢的坏习惯:ORDER BY序数

SQL:order by