mysql union 查询排序与 union 顺序的关系
您的问题是 mysql 8.0 中,union 查询的结果排序与 union 本身顺序不一致。在较早的 mysql 版本中,这种排序结果是符合预期的。
原因
在 mysql 8.0 中,union 查询采用了新的排序算法,该算法以每个查询结果集中匹配条件的列为依据进行排序。这意味着,如果某个查询结果集中匹配了多个条件,则它在 union 结果中的顺序会优先于匹配较少条件的查询。
解决方案
为了按照 union 顺序返回结果,可以使用以下技巧:
1. case when 语句
您可以使用 case when 语句为每个 union 查询结果分配一个优先级序号:
select `id` ,`class_id` ,`active` ,`add_time` ,`show_time` ,`url_prefix` ,`subject` from `glfr_article` where `active` = '1' and `show_time` < 1655278257 and ( `subject` like '%mysql%' or `subject` like '%导入%' or `subject` like '%导出%' ) order by case subject like '%mysql导入导出%' when true then 0 else 1 end, case subject like '%mysql%' when true then 0 else 1 end, case subject like '%导入%' when true then 0 else 1 end, case subject like '%导出%' when true then 0 else 1 end ;
2. 匹配词个数排序
如果您需要根据匹配词的个数降序排序,可以使用如下查询:
SELECT `id` ,`class_id` ,`active` ,`add_time` ,`show_time` ,`url_prefix` ,`subject` ,(length(replace(replace(replace(subject, 'MySQL', 'MySQL_'), '导入', '导入_'), '导出', '导出_')) - length(subject)) as 'point' FROM `glfr_article` WHERE `active` = '1' AND `show_time` < 1655278257 AND ( `subject` LIKE '%MySQL%' OR `subject` LIKE '%导入%' OR `subject` LIKE '%导出%' ) ORDER BY length(replace(replace(replace(subject, 'MySQL', 'MySQL_'), '导入', '导入_'), '导出', '导出_')) - length(subject) desc
以上就是MySQL 8.0 中,union 查询结果排序与 union 顺序不一致,如何解决?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号