2012-09-20 58 views
1

我有一個網頁,它有一個表中的新聞數據。mysql按日期和優先順序排列

在許多情況下,我使用下面的SQL:

SELECT * FROM table ORDER BY insertDate DESC 

秩序。

ID|priority|insertDate 
1 |NULL |2012-09-16 
2 |NULL |2012-09-17 
3 |NULL |2012-09-18 
5 |NULL |2012-09-19 
5 |NULL |2012-09-20 
4 |1  |2010-05-10 - this is way back in the futurer 

但用戶想優先考慮1條新聞。如果我用

SELECT * FROM table ORDER BY priority ASC ,insertDate DESC 

它不能正常工作,我該如何必須使用才能得到結果

ID|priority|insertDate 
4 |1  |2010-05-10 
1 |NULL |2012-09-16 
2 |NULL |2012-09-17 
3 |NULL |2012-09-18 
5 |NULL |2012-09-19 
5 |NULL |2012-09-20 

回答

4

Use coalesce設置有效的值設置爲null優先行:

SELECT * 
FROM table 
ORDER BY 
    coalesce(priority,0) ASC , 
    insertDate DESC 

編輯

重新讀取您的闕我看到正確的順序是DESC而不是ASC:

coalesce(priority,0) DESC , 

此外,請注意@yshavit的評論。爲了提高性能,您可以將兩個選擇中的查詢拆分爲第一個非空值的查詢。

記得比當你創建你這個新領域can set to it a default value,這將避免​​3210和union

data_type [NOT NULL | NULL] [DEFAULT default_value] 
+0

注意,這意味着查詢將無法使用索引進行排序。如果你希望所有的NULL都是最後一個而不是第一個,那麼最好有兩個SELECT,其中一個的優先級不爲空,一個的優先級爲空,並且UNION它們。我現在無法嘗試,但我想這將能夠使用索引。 – yshavit

+0

SELECT * FROM表 ORDER BY coalesce(priority,0)DESC, insertDate DESC – Infira

0
SELECT * 
FROM table 
ORDER BY 
    if(priority IS NULL,'0',priority) ASC , 
    insertDate DESC;