K
K
Konstantin B.2020-02-20 15:48:07
MySQL
Konstantin B., 2020-02-20 15:48:07

MySQL sorting in different directions in a query?

Hello. I can’t cope with the task, either I’m stupid, or maybe I don’t know everything and I can’t come up with a solution.
The essence is this, there is a table of events, the event has a date. Initially, the list was sorted in one direction from the most relevant events to the oldest ones. But the number of new events has increased and it has become unclear where something is closer to today. As a result, we came to the conclusion that future games in the search results should be reversed, that is, there should be the following chronology Today

= 20.02.2019

So the list should be built like this
--- Here are the future
02.21.2019
02.22.2019
02.23.2019
02.24.2019 --- If there are no future games, the past ones go on 02/19/2019
02/18/2019
02/17/2019 02/16/2019
02/15/2019
_

select *
    where `games`
from `games`
order by CASE WHEN date > NOW() THEN date END DESC, date DESC, `date` desc

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lazy @BojackHorseman MySQL, 2020-02-20
Tag

reduce to int (unixtime) and multiply by -1 if date > NOW().
and sort by that result. the truth will be past the sorting index.

T
ThunderCat, 2020-02-20
@ThunderCat

select * from (
    (select * from `games`
where  date > now()
order by date desc)
union
(select * from `games`
where  date < now()
order by date )
              ) a
limit 0,50

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question