简体   繁体   中英

Mysql return today's result before future date results

SELECT `user_appoint`.`ApptDateTime` AS ApptDate,`user_appoint`.`id` AS appt_id,        `user_appoint`.`ref_no` AS ref_no, `user_appoint`.`status_id` AS status_id,  `user_det`.`pass_no`, `user_det`.`f_name` AS fname, `user_appoint`.`date`, `user_det`.`l_name` AS lname, `user_det`.`dob` AS dob, `tbl_pi`.`Pi`, `tbl_vesselmaster`.`id` AS Vid, `user_det`.`id` AS user_id, `user_appoint`.`dr_comments` AS Remarks
FROM (`user_det`)
JOIN `user_appoint` ON `user_appoint`.`u_id` = `user_det`.`id`
LEFT JOIN `tbl_pi` ON `user_appoint`.`id` = `tbl_pi`.`ApptId`
JOIN `tbl_rank` ON `user_appoint`.`rank` = `tbl_rank`.`rank_id`
JOIN `tbl_typeofmedical` ON `tbl_typeofmedical`.`Id`=`user_appoint`.`purpose`
JOIN `tbl_vesselmaster` ON `tbl_vesselmaster`.`id` = `user_appoint`.`vessel`
JOIN `tbl_clinic_list` ON `tbl_clinic_list`.`Id` = `user_appoint`.`ClinicId`
JOIN `pate_status` ON `pate_status`.`id`=`user_appoint`.`status_id`
LEFT JOIN `tbl_doctorlist` ON `tbl_doctorlist`.`id`=`user_appoint`.`DrId`
LEFT JOIN `tbl_fleetvessel` ON `tbl_fleetvessel`.`VesselId` = `user_appoint`.`vessel`
WHERE `user_appoint`.`void` =  0
AND `user_appoint`.`comp_id` =  '123'
AND `user_det`.`3cc_id`  LIKE '%%'
AND `user_appoint`.`ref_no`  LIKE '%%'
AND  `user_appoint`.`DrId`  LIKE '%%'
AND  `tbl_fleetvessel`.`FleetId`  LIKE '%%'
AND  `ApptDateTime`  LIKE '%%'
ORDER BY `user_appoint`.`ApptDateTime` DESC
LIMIT 15

This is myquery which return following result

ApptDate                      f_name       l_name  
--------------               -------      -------
13-11-2015                    xyz           pqr
06-11-2015                    abc           uio
04-11-2015                    qwe           jkl

I want the table to show today's result on top followed by future results and then the rest of results.

Just change the order by clause of your query:

ORDER BY DATE_FORMAT(`user_appoint`.`ApptDateTime`, '%d-%m-%Y') = DATE_FORMAT(NOW(), '%d-%m-%Y') DESC, `user_appoint`.`ApptDateTime` > NOW() DESC, `user_appoint`.`ApptDateTime` DESC

That way the first result is the one where the date matches today, the next results are those where the date is greater than today (=in the future) and then the rest in descending order.

Simply use CASE WHEN with your conditions in your ORDER BY:

ORDER BY
  CASE
    WHEN DATE(user_appoint.ApptDateTime) = CURDATE() THEN 1
    WHEN DATE(user_appoint.ApptDateTime) > CURDATE() THEN 2
    ELSE 3
  END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM