2014-03-07 116 views
1

在一個錶行中,我有一列product_price。如果產品的價格較低(折扣),則折扣價格列在sql結果中設置爲別名。如果產品沒有折扣(沒有更低的價格),這個colum discount_price是空的。MySQL按兩列的價值排序

我想要的是訂購這個集合,並按照來自product_price(如果discount_price爲null)和discount_price的值進行排序。

例如

 

---------------------------------------- 
ID product_price discount_price 
---------------------------------------- 
1  4800   NULL 
2  13000   4400 
3  3300   NULL 
4  10500   9600 
5  1600   NULL 
 

我想訂購的深淺時,得到這樣的結果:(如果discount_price爲空,檢查PRODUCT_PRICE值,如果discount_price是NOT_NULL在discout_price檢查值)

 

---------------------------------------- 
ID product_price discount_price 
---------------------------------------- 
4  10500   9600 
1  4800   NULL 
2  13000   4400 
3  3300   NULL 
5  1600   NULL 
+0

嘗試,如果有可能'ORDER BY IFNULL(discount_price,PRODUCT_PRICE)'我NT知道,如果這樣的事情是可能的,但它是值得一試 –

+0

你希望的結果沒有意思,他們沒有按照你所說的順序。 –

+0

您是否嘗試過構建查詢? –

回答

1

試試這個:

SELECT * FROM my_table 
ORDER BY IFNULL(discount_price, product_price); 
1

試試這個

SELECT * FROM table1 
ORDER BY CASE WHEN discount_price IS NULL  then PRODUCT_PRICE 
       WHEN discount_price IS NOT NULL then discount_price 
    END DESC 

DEMO HERE

+0

那麼,這基本上是'IFNULL'乾的......您是否嘗試過'IFNULL'方法?代碼將會更清晰和更短。我猜也快 –