P
P
Pavel Dovlatov2015-11-16 19:02:19
MySQL
Pavel Dovlatov, 2015-11-16 19:02:19

Suggest an implementation of a sort method for a MySQL query?

I was puzzled by such a question:
There are fields, conditionally, dt_start, dt_end, which store the timestamp of the beginning and end of a certain event.
It is required to sort in a MySQL query such that the events that are happening now are listed first, then the upcoming events are listed in ascending order of their date, and then the past ones, in descending order of their date.
Not interested in the options "union", "sort the result in the code", etc.
Only manipulations with the ORDER BY field.
I am interested in the fundamental possibility of writing such a query (I will be glad for an example), or the conclusion that such a query cannot be built.
Think of it as just a mental workout.
Thank you. :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2015-11-16
@MysteryDragon

What is the difficulty of this task?

SELECT *
    FROM `table`
    ORDER BY IF(NOW() BETWEEN `dt_start` AND `dt_end`, 0,
                IF (NOW() < `dt_start`, 1, 2)),
             ABS(DATEDIFF(NOW(), `dt_start`)), 
             `dt_start`, `dt_end`

A
Aleksey Ratnikov, 2015-11-16
@mahoho

It is impossible to do this without UNION .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question