组合查询 union 怎么排序,需要注意的点?
UNION 操作符用于连接两个以上的 SELECT 语句的结果组合到一个结果集合中。多个 SELECT 语句会删除重复的数据。
但是 UNION ALL 不会删除重复的数据。
(SELECT
d.bingren_name name,
d.bingren_id no,
d.bingren_Rid cardId,
d.bingren_Phone phone,
CONCAT((SELECT
section_name
FROM
personnel_section_code c
WHERE
c.section_no =
md.Subject_no),"-",ps.section_name) subjectName,
da.typeName guaHaoType,
da.valueName money,
mr.state guaHaoState,
mr.visitTime jiuZhenTime,
mr.time yuYueTime,
w.avatar,
w.nickName niceName,
h.address,
md.Doctor_name doctorName,
pi.Title_no title,
mr.id describeId ,
ps.section_no sectionNo ,
left(dt.date_begin, 5) beginTime,
left(dt.date_end ,5) endTime,
mr.guahaoDay
FROM
menzhen_register mr,
data_doctortime dd,
data_patient d,
menzhen_doctordepartment md,
data_dictionary da,
personnel_section_code ps,
personnel_information pi,
wx w,
huanzheregister h,
data_times dt
WHERE
dt.date_id = dd.doctor_rid AND
mr.doctorTimeId = dd.id
AND mr.bingRenId = d.bingren_id
AND dd.doctor_no = md.Doctor_no
AND md.Doctor_type = da.id
AND md.Doctor_no = pi.doctorId
AND ps.section_no = pi.Section_no
AND w.id = d.bingren_card
AND h.id = d.detailsId
AND mr.guahaoDay = CURDATE()
AND LEFT(dt.date_begin,2) = LEFT(curtime(),2) ORDER BY yuYueTime LIMIT 1000)
UNION
(SELECT
d.bingren_name name,
d.bingren_id no,
d.bingren_Rid cardId,
d.bingren_Phone phone,
CONCAT((SELECT
section_name
FROM
personnel_section_code c
WHERE
c.section_no =
md.Subject_no),"-",ps.section_name) subjectName,
da.typeName guaHaoType,
da.valueName money,
mr.state guaHaoState,
mr.visitTime jiuZhenTime,
mr.time yuYueTime,
w.avatar,
w.nickName niceName,
h.address,
md.Doctor_name doctorName,
pi.Title_no title,
mr.id describeId ,
ps.section_no sectionNo ,
left(dt.date_begin, 5) beginTime,
left(dt.date_end ,5) endTime,
mr.guahaoDay
FROM
menzhen_register mr,
data_doctortime dd,
data_patient d,
menzhen_doctordepartment md,
data_dictionary da,
personnel_section_code ps,
personnel_information pi,
wx w,
huanzheregister h,
data_times dt
WHERE
dt.date_id = dd.doctor_rid AND
mr.doctorTimeId = dd.id
AND mr.bingRenId = d.bingren_id
AND dd.doctor_no = md.Doctor_no
AND md.Doctor_type = da.id
AND md.Doctor_no = pi.doctorId
AND ps.section_no = pi.Section_no
AND w.id = d.bingren_card
AND h.id = d.detailsId
ORDER BY
yuYueTime DESC LIMIT 1000);
guaHaoState,
yuYueTime desc,
jiuZhenTime desc);
注意:
- union 的查询语句,需要用括号括住,如果需要排序(order by )就需要加上 limit 。