博客
关于我
mysql union (all) 后order by的排序失效问题解决
阅读量:736 次
发布时间:2019-03-22

本文共 1211 字,大约阅读时间需要 4 分钟。

针对SQL查询中UNION ALL操作导致的排序问题,我们可以通过以下方法解决问题。

问题描述:

在使用UNION ALL操作合并两个SELECT结果时,发现合并后的结果排序不稳定,导致输出顺序混乱。尽管已在查询中添加排序条件ORDER BY rate,但结果仍不符合预期。

解决方案:

为了确保排序稳定性,可以在结果集中添加一个额外的字段,并在排序时优先基于该字段。这种方法可以保证在合并后的结果中,数据按照预期顺序排列。

优化后的查询示例:

SELECT * FROM (
SELECT SUM(c.overtime_num) AS delay_num,
ROUND((SUM(c.total_num) - SUM(c.overtime_num)) * 100 / SUM(c.total_num), 2) rate,
'全网' AS reaCode,
0 AS od
FROM calc_vmap_repair_timely_rate_mon_stat c
WHERE c.`type` = 22
AND c.MONTH BETWEEN '2019-01' AND '2019-01'
) t1
UNION ALL
SELECT SUM(c.overtime_num) AS delay_num,
ROUND((SUM(c.total_num) - SUM(c.overtime_num)) * 100 / SUM(c.total_num), 2) rate,
c.motorcade_area_code AS reaCode,
1 AS od
FROM calc_vmap_repair_timely_rate_mon_stat c
WHERE c.`type` = 22
AND c.MONTH BETWEEN '2019-01' AND '2019-01'
GROUP BY c.motorcade_area_code
) t2
ORDER BY od, rate;

解决方法说明:

  • 添加稳定排序字段:在两个SELECT结果中分别添加一个字段od,分别设置为01
  • 优先排序稳定字段:在最终的ORDER BY中,先按od字段排序,再按rate排序。
  • 确保唯一性:通过UNION ALL操作合并结果时,确保每个结果集中的数据具有唯一性,避免重复记录。
  • 优势分析:

    • 排序稳定性:通过在结果集中添加一个额外的排序依据字段,确保了合并后的数据按照预期顺序排列。
    • 查询性能:添加的字段不会显著影响查询性能,尤其是当od字段只用于排序时。
    • 可读性:代码结构更加清晰,便于其他开发人员理解和维护。

    这种方法有效解决了UNION ALL操作后排序问题,同时保持了查询的高效性。

    转载地址:http://koywk.baihongyu.com/

    你可能感兴趣的文章
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
    查看>>
    NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
    查看>>
    Node JS: < 一> 初识Node JS
    查看>>
    Node-RED中使用JSON数据建立web网站
    查看>>
    Node-RED中使用json节点解析JSON数据
    查看>>