查询中的Mysql ORDER BY条件取决于日期

时间:2012-06-22 08:09:33

标签: mysql if-statement sql-order-by conditional case

我有一个mysql查询,它获取行到设计列表。在这个列表中,我们有“普通”行,按照它们的id排序,“特殊”行按“special_end”排序(这是日期,在所有行中它现在是NULL)参数。因此,结果中的“特殊”行应该高于“正常”。

立即查询:

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排序,
  • 如果d.special_end< = DATE(NOW()) - >按ID DESC排序。

示例(id - row - 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

但没有结果。

感谢您的帮助。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

当存在多个Group by或排序要求时,始终使用UNION拆分查询。 只需使用UNION操作符拆分查询并进行排序。如下所示

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