2012-06-22 73 views
3

我有一個mysql查詢,它獲取行到設計列表。在這個列表中,我們有按照它們的ID排序的「正常」行,以及按「special_end」排序的「特殊」行(這是日期,所有行中它現在是NULL)參數。因此,結果中的「特殊」行應高於「正常」。查詢中的Mysql ORDER BY條件取決於日期

查詢現在:

SELECT d.*, DATE_FORMAT(_created, '%d.%m.%Y') as _created_human, count(dp.id) photos_cnt, u.id user_id, u.class_name user_class_name, u.full_name user_full_name 
FROM designs d 
LEFT JOIN design_photo dp ON d.id=dp.design_id 
LEFT JOIN cms_user u ON d.cms_user_id=u.id 
WHERE 1=1 AND d.status_id=1 AND d.published=1 AND u.cms_user_status_id=1 
GROUP BY d.id 
ORDER BY d.special_end DESC, id DESC 
LIMIT 20 OFFSET 0 

我需要在此查詢升級ORDER BY塊與special_end參數與行排序條件:

  • 如果d.special_end> = DATE(NOW() ) - >按d.special_end排序DESC,
  • if if.special_end < = DATE(NOW()) - >按ID DESC排序。

例(ID - 排 - special_end):

515 design4 2012-07-21 
514 design3 2012-06-30 
526 design5 null 
513 design2 2012-05-30 (this date is <= DATE(NOW())) 
512 design1 null 
511 design0 null 
. 
. 
. 

我已經試着寫類似

ORDER BY CASE d.special_end WHEN d.special_end >= DATE(NOW()) THEN d.special_end WHEN d.special_end <= DATE(NOW()) THEN d.id END DESC 

ORDER BY IF(d.special_end >= DATE(NOW()), d.special_end, d.id) DESC 

,但沒有結果。

感謝您的幫助。

回答

3

訂購一個條件可能是非常緩慢的,我寧願使用UNION來達到相同的結果:

SELECT t.* FROM (
    (
     SELECT d.*, DATE_FORMAT(_created, '%d.%m.%Y') as _created_human, count(dp.id) photos_cnt, u.id user_id, u.class_name user_class_name, u.full_name user_full_name 
     FROM designs d 
     LEFT JOIN design_photo dp ON d.id=dp.design_id 
     LEFT JOIN cms_user u ON d.cms_user_id=u.id 
     WHERE d.special_end >= DATE(NOW()) AND d.status_id=1 AND d.published=1 AND u.cms_user_status_id=1 
     GROUP BY d.id 
     ORDER BY d.special_end DESC 
    ) UNION (
     SELECT d.*, DATE_FORMAT(_created, '%d.%m.%Y') as _created_human, count(dp.id) photos_cnt, u.id user_id, u.class_name user_class_name, u.full_name user_full_name 
     FROM designs d 
     LEFT JOIN design_photo dp ON d.id=dp.design_id 
     LEFT JOIN cms_user u ON d.cms_user_id=u.id 
     WHERE (d.special_end < DATE(NOW()) OR d.special_end IS NULL) AND d.status_id=1 AND d.published=1 AND u.cms_user_status_id=1 
     GROUP BY d.id 
     ORDER BY d.id DESC 
    ) 
) t LIMIT 20 OFFSET 0 
+0

感謝您的回答。在LIMIT之前應該有一個極值「)」(否則 - 語法錯誤信息)。現在我得到「每個派生表都必須有自己的別名」消息。 –

+0

它可能會與'UNION ALL'一起工作。我不會相信'UNION'。 –

+0

@VasiliyToporov哦,我道歉,修復。 @ypercube'UNION ALL'也可以使用,但爲什麼不信任'UNION'? – jkrcma

2

始終與聯盟中分裂查詢時曾經有多個組或排序要求。 只需將您的查詢與UNION操作員分開,並進行排序。如下所示

Select * from Something where <condtion> order by 1 desc 
UNION 
Select * from Something where <condtion> order by 2 desc