2012-07-05 76 views
12

我在MySQL中有一個問題,是否正確。但是這本書的代碼有點不同。這是1的順序是什麼?

書:

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; 
+0

StackOverflow的 - 爲什麼ü不易格式化??? :( – Master 2012-07-05 23:03:36

+2

只要你閱讀格式化幫助,很容易格式化代碼:) – Ryan 2012-07-05 23:04:22

+0

只需在開始行上添加4個空格來製作一個代碼塊。但確保在第一個之前有一個空行。您可以在編輯器的幫助圖標上看到更多信息。 – rcdmk 2012-07-05 23:04:53

回答

23

order by 1指的是「我選擇的第一個字段順序」 - 也就是說,在這種情況下,同爲order by playerno,因爲playerno是列表中的第一個字段。

編輯:做一個快速瀏覽一下SQL-92 standard草案證實了這一點:

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是,似乎適用的一個。雖然我確信這個草案和標準的最終文本之間至少有一些變化(更不用說在一個版本的標準和另一個版本之間),但這種基本的東西似乎不大可能會改變(可能永遠)。

+0

謝謝!得到它了 !很好,很清楚! – Master 2012-07-05 23:08:12

+0

而不是合規性標準,讓我們用MySQL自己的文檔來備份:https://dev.mysql.com/doc/refman/5.7/en/select.html關鍵字:'order by 2' – Sinkeat 2017-08-10 08:03:15

5

這被稱爲「ORDER BY ordinal」,基本上按該位置的列排序。按1排序意味着按第一個選定的列排序。在你的例子中,這將相當於說ORDER BY playerno

我不會這樣做,因爲它不清楚它引用哪個列,如果列順序發生變化,查詢將返回不同的結果。

更多資源:

Quick Tip: Order By 1 Desc

Bad habits to kick : ORDER BY ordinal

SQL: order by

+0

..... .................正好! – Master 2012-07-06 00:07:20