2012-07-25 85 views
0

如果我有兩列,價格(full_price,sales_price)和這些列中都有數字。我知道sql語句可以按多個順序執行,但當這些列中有值時,它是如何工作的?mySQL statement ORDER BY multiple columns

("SELECT * FROM table ORDER BY full_price,sales_price DESC") 

我該如何做到這一點,它會選擇兩列中的最小值?它會根據所選列在full_price和sales_price之間的順序放置數據?

注意:有時sales_price沒有價值。

感謝

編輯:

id full_price  sales_price 
1  23     42   
2  342    200 
3  1 
4  10     8 

我試圖做的是這些數字,我可以用最低的價格相關的輸出數據。

的順序應該是:

3,4,1,2 

原因:

3: 1 
4: 8 
1: 23 
2: 200 
+2

你能舉個例子嗎? – 2012-07-25 05:06:58

+0

我編輯顯示一個例子,謝謝 – hellomello 2012-07-25 05:10:32

回答

4

假設空白sales_price是NULL和full_price不能爲空:

select ... 
from ... 
where ... 
order by case 
    when sales_price is null then full_price 
    else least(full_price, sales_price) 
end 

你可能想增加一個次要排序鍵搞定一致,來自關係的明智結果。

+0

我將如何添加另一個排序鍵?我是否將其添加到案例中,還是在結束後? – hellomello 2012-07-25 05:16:26

+0

我嘗試了所有答案,這一個工作得最好。謝謝 – hellomello 2012-07-25 05:20:41

+1

@andrewliu:你會在'end'之後添加第二個排序鍵:'按大小寫排序... end,some_other_column' – 2012-07-25 05:29:42

1
SELECT * FROM table 
ORDER BY case when sales_price is null or full_price is null 
       then 0 
       when full_price > sales_price 
       then sales_price ASC 
       else full_price ASC 
     end 
0

如果您想根據FULL_PRICE和sales_price的差異導致再試試:

SELECT * 
FROM table 
ORDER BY ABS(full_price - IF(sales_price IS NULL, 0, sales_price)) ASC 

或如果你想要基於compari的結果FULL_PRICE和sales_price的錫永然後嘗試:

SELECT * 
FROM table 
ORDER BY IF(full_price < IF(sales_price IS NULL, 0, sales_price), 
      full_price , sales_price) ASC