2015-09-23 68 views
0

我有產生由以下邏輯有序選擇查詢的問題:MySQL的ORDER BY兩個字段條件

SELECT * FROM Products WHERE 1 ORDER BY Stock > 0, Price DESC 

表樣品:

+---------+-------+-------+ 
| Product | Price | Stock | 
+---------+-------+-------+ 
| Car  | 3500 | 30 | 
| Boat | 7500 |  6 | 
| Bike | 150 | 220 | 
| Plane | 55000 |  0 | 
+---------+-------+-------+ 

期望的結果是,該表將被訂購價格如果庫存值大於0.

所以結果應該是:

+---------+-------+-------+ 
| Product | Price | Stock | 
+---------+-------+-------+ 
| Boat | 7500 |  6 | 
| Car  | 3500 | 30 | 
| Bike | 150 | 220 | 
| Plane | 55000 |  0 | 
+---------+-------+-------+ 

任何想法?

回答

2

在MySQL中比較的結果是01。所以Stock > 01如果true。和10。因此,無論使用

ORDER BY Stock = 0 ASC, Price DESC 

ORDER BY Stock > 0 DESC, Price DESC 

ORDER BY case when Stock > 0 
       then 1 
       else 2 
     end, 
     Price DESC