1

It is necessary to make a complex selection from the table with sorting for different conditions. When I make two requests separately, then everything works, and if I combine, it outputs without sorting - by the growth of the key field of the table

(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)
Barmar
  • 741,623
  • 53
  • 500
  • 612
Dr.Noname
  • 73
  • 10

2 Answers2

0

union all outputs the results of each query serially - your rows would be ordered within each query result but not overall.

To effect an overall ordering, move the order by outside the two queries by creating an outer query to wrap the union all result.

To effect ordering that's different depending on which half of the union all the result came from, add information to the rows about the source of the row and use that to get the specific ordering:

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

If you need to exclude source from the query output, you could wrap the above and another outer query that just selects all columns other than source.

I've also removed the unnecessary brackets.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

I found a solution

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
Dr.Noname
  • 73
  • 10