问题
I had a question in MySQL, did it correctly. But the book code differs a little.
Book:
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;
What is this order by 1 ?
My code also works and is almost the same except:
select playerno, datediff(coalesce(end_date, current_date) AS Data,
order by Data;
回答1:
order by 1
means "order by the first field I selected" -- i.e., in this case, the same as order by playerno
, because playerno
was the first field in the list.
In case you want the official wording, here's what the SQL-92 standard1 says:
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>.
In this case, b
is the one that seems to apply.
1. This quote is from a freely-available draft rather than the approved standard. While I'm sure there are at least a few changes between this draft and the final text of the standard (not to mention between one version of the standard and another) it seems unlikely that something this fundamental would change (probably ever).
回答2:
This is known as "ORDER BY ordinal", basically order by the column in that position. Order by 1 means order by the first selected column. In your example, it would be the equivalent of saying ORDER BY playerno
I wouldn't recommend doing it this way though as it's not clear what column it's referencing and if the column order changes the query will return different results.
More resources:
Quick Tip: Order By 1 Desc
Bad habits to kick : ORDER BY ordinal
SQL: order by
来源:https://stackoverflow.com/questions/11353688/what-is-this-order-by-1