21

我在 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;

这个 1 的顺序是什么?

我的代码也可以工作并且几乎相同,除了:

select playerno, datediff(coalesce(end_date, current_date) AS Data,
order by Data;
4

2 回答 2

35

order by 1表示“按我选择的第一个字段排序”——即,在这种情况下,与 , 相同order by playerno,因为playerno它是列表中的第一个字段。

如果您想要官方措辞,SQL-92 标准1是这样说的:

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>.

在这种情况下,b似乎适用。

不过,较新版本的 SQL 标准已删除此功能,因此新代码通常应避免使用它。基于 SQL 的数据库服务器已经弃用它一段时间了,但为了向后兼容,大多数服务器仍然支持它。同时,他们已弃用它的事实表明他们不再认为这是他们真正需要支持的功能,因此可以随时将其删除而无需进一步警告(例如,如果他们在该部分发现错误在他们的代码中,他们可能决定修复错误的最佳方法是禁用该功能)。


1. 此报价来自免费提供的草案,而不是批准的标准。虽然我确信这个草案和标准的最终文本之间至少有一些变化(更不用说标准的一个版本和另一个版本之间),但这个基本的东西似乎不太可能在草案和最终版本之间发生变化标准。
于 2012-07-05T23:04:22.760 回答
7

这被称为“ORDER BY ordinal”,基本上按该位置的列排序。按 1 排序表示按第一个选定列排序。在您的示例中,这相当于说ORDER BY playerno

我不建议这样做,因为不清楚它引用的是哪一列,如果列顺序发生变化,查询将返回不同的结果。

更多资源:

快速提示:按 1 Desc 订购

要踢的坏习惯 : ORDER BY ordinal

SQL:按顺序排列

于 2012-07-05T23:12:45.467 回答