2017-03-07 51 views
2

今天我遇到問題。這是我的工作表:通過限制混淆MySQL訂單

select id,name,is_active from jobs order by `is_active` desc

和結果是:

enter image description here

但是,當我想要得到前10個記錄我選擇這樣的:

select id,name,is_active from jobs order by `is_active` desc limit 10 offset 0

並且結果是

enter image description here

爲什麼id是從14到5,應該是1到10.誰能告訴我爲什麼?

+0

http://stackoverflow.com/questions/8746519/sql-what-is-the-default-order-by-of-queries –

+0

https://dev.mysql.com/doc/refman/ 5.7/en/order-by-optimization.html –

回答

2

如果你想要更深的順序,你必須明確地要求它,否則結果將是不可預知的。所以,如果你也需要ID順序,請添加它。

select id,name,is_active from jobs order by `is_active` desc, id asc limit 10 offset 0 
+0

謝謝。我現在明白了。 – DengDeng

1

在MySQL中,如果沒有明確指定,那麼順序是任意的。您應該嘗試order by id asc

+0

謝謝。現在它工作正常。 – DengDeng

1

您需要ORDER BY使用多列,例如:

SELECT id, name, is_active 
FROM jobs 
ORDER BY `is_active` DESC id ASC; 
+0

謝謝。現在它工作正常。 – DengDeng

1

如果您需要保留的結果降序排列,並且仍然只希望10分最後一個ID的,你應該兩次排序的結果。

以下查詢將按升序對結果進行排序,並將結果限制爲10(即括號內的查詢)。它仍然會按升序排序,我們對此並不滿意,所以我們再分類一次。現在我們在最後一行有最新的結果。

select t.id, t.name, t.is_active 
from 
    (select id, name, is_active 
    from jobs 
    order by `is_active` asc limit 10) t 

order by t.is_active desc;