日常开发中,如果实用UNION ALL合并两个已经排好序的结果集的时候,需求是第二个结果集数据排在第一个结果集数据下面,单纯的实用order by是无效的,因为order by的优先级比UNION ALL低。
SELECT `referralid`, `referral_time`, `referral_doctor_uid`, `reception_doctor_uid`, `reception_doctor_name`, `reception_doctor_hospital`, `referral_doctor_hospital`, `referral_doctor_name`, `referral_status`, `daozhen_status`, `pid`, `user_type`, `referralid`, `patient_uid`, `patient_tel`, `patient_name`, `patient_idcard`, `updated_at`, `zhuan_type`, `return_created_at`, `return_referral_status`, `return_daozhen_status`, `return_referral_time`, `referal_type`, `global_id` FROM `hdw_referral` WHERE ( ( `reception_doctor_uid` = 51619 AND `reception_doctor_uid` > 0 AND `zhuan_type` = 2 ) OR ( `referral_doctor_uid` = 51619 AND `referral_doctor_uid` > 0 ) ) union SELECT `referralid`, `referral_time`, `referral_doctor_uid`, `reception_doctor_uid`, `reception_doctor_name`, `reception_doctor_hospital`, `referral_doctor_hospital`, `referral_doctor_name`, `referral_status`, `daozhen_status`, `pid`, `user_type`, `referralid`, `patient_uid`, `patient_tel`, `patient_name`, `patient_idcard`, `updated_at`, `zhuan_type`, `return_created_at`, `return_referral_status`, `return_daozhen_status`, `return_referral_time`, `referal_type`, `global_id` FROM `hdw_referral` WHERE referralid <5; ORDER BY `referralid` desc;
需要根据referralid 进行排序,你会发现根本没有根据这个进行排序
解决方案的巧妙之处就是,利用一个自定义的字段实现两个结果集的合并后排序。