2012-04-11 43 views
4

我用我的數據庫下面的查詢,MySQL查詢,以顯示與當前日期在頂部和記錄人按降序排列

SELECT b.sales_id,b.category_id,b.sale_starts,b.sale_ends 
FROM tbl_sales b WHERE b.active=1 
UNION 
SELECT b.sales_id,b.category_id,b.sale_starts,b.sale_ends 
FROM tbl_sales b INNER JOIN tb_category c ON b.category_id=c.cat_id 
WHERE c.cat_keyword LIKE 'a' ORDER BY sale_ends DESC 

,並得到如下結果,

sales_id | category_id   |sale_starts | sale_ends 
----------|---------------------|------------|-------------- 
1  | 10    | 2012-03-31 | 2012-04-30  
2  | 11    | 2012-03-22 | 2012-04-27 
3  | 25    | 2012-03-31 | 2012-04-25 
4  | 12    | 2012-04-05 | 2012-04-11 

現在我需要得到如下結果,即sale_ends必須顯示在訂單頂部(假設今天的日期/當前日期爲2012-04-11),如下所示:

sales_id  | category_id   |sale_starts | sale_ends 
    ----------|---------------------|------------|-------------- 
    4  | 12    | 2012-04-05 | 2012-04-11 (today's date) 
    1  | 10    | 2012-03-31 | 2012-04-30  
    2  | 11    | 2012-03-22 | 2012-04-27 
    3  | 25    | 2012-03-31 | 2012-04-25 

需要幫助,在此先感謝。

回答

5

試試這個ORDER BY子句條件 -

ORDER BY IF(sale_ends = DATE(NOW()), 0, 1), sale_ends DESC 
+1

非常感謝,那工作正常.. – 2012-04-11 06:28:23

3

你可以用整個事情的另一選擇和使用ORDER BY

SELECT * FROM (  
    SELECT b.sales_id,b.category_id,b.sale_starts,b.sale_ends 
    FROM tbl_sales b WHERE b.active=1 
    UNION 
    SELECT b.sales_id,b.category_id,b.sale_starts,b.sale_ends 
    FROM tbl_sales b INNER JOIN tb_category c ON b.category_id=c.cat_id 
    WHERE c.cat_keyword LIKE 'a' ORDER BY sale_ends DESC 
) AS all_sales 
ORDER BY (sale_ends=CURDATE()) DESC, sale_ends DESC 
+0

這也工作得很好,感謝 – 2012-04-11 06:29:01

相關問題