I have one mysql query, which gets rows to designs list. In this list we have “normal” rows, which are sorted by their id, and “special” rows which are sorted by “special_end” (this is date, in all rows it’s NULL now) parameter. So, “special” rows in result should be higher than “normal”.
Query now:
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
I need to upgrade ORDER BY block in this query to sort rows with special_end parameter with condition:
- if d.special_end >= DATE( NOW() ) -> sort by d.special_end DESC,
- if d.special_end <= DATE( NOW() ) -> sort by id DESC.
Example (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
.
.
.
I’ve already try to write something like
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
or
ORDER BY IF(d.special_end >= DATE( NOW() ), d.special_end, d.id) DESC
but no result.
Thanks for your help.
Ordering by a condition might be terribly slow, I’d rather use
UNIONto achieve the same result: