UNION ALL结果未正确排序

时间:2017-11-18 16:39:25

标签: mysql union-all

有必要从表中进行复杂的选择,并根据不同的条件进行排序。当我单独提出两个请求时,一切正常,如果我合并,它输出而不排序 - 通过表格的关键字段的增长

(SELECT * 
 FROM `user` 
 WHERE `user`.`rank_golos` >=22.1 
 order by `user`.rank_yearnub DESC, `user`.rank_golos DESC) 
UNION ALL 
(SELECT * 
 FROM `user` 
 WHERE `user`.`rank_golos` <22.1 and `user`.`rank_golos` >0 
 order by `user`.rank_golos DESC, `user`.rank_yearnub DESC)

2 个答案:

答案 0 :(得分:0)

union all按顺序输出每个查询的结果 - 您的行将在每个查询结果中排序,但不是整体。

要实现整体排序,请通过创建外部查询来包装order by结果,将union all 移到两个查询之外。

要根据结果的union all的哪一半来实现不同的排序,请向行的行添加有关行的信息,并使用它来获取特定的顺序:

SELECT * FROM (
    SELECT *, 1 as source 
    FROM `user` 
    WHERE `user`.rank_golos >= 22.1 
    UNION ALL 
    SELECT *, 2
    FROM `user` 
    WHERE `user`.rank_golos < 22.1 and `user`.rank_golos > 0
) x
order by
  case when source = 1 then rank_yearnub else rank_golos end DESC,
  case when source = 1 then rank_golos else rank_yearnub end DESC

如果您需要从查询输出中排除source,则可以包含上面和另一个外部查询,该查询只选择其他而不是source的所有列。

我还删除了不必要的括号。

答案 1 :(得分:0)

我找到了解决方案

select * from user
where rank_golos >0
order by rank_golos >=22.1 desc, 
  if (rank_golos >=22.1, rank_yearnub, rank_golos) desc,
  if (rank_golos >=22.1, rank_golos, rank_yearnub) desc