Domanda

I have a list of events in events_table, i store date of event in yyyy-mm-dd format. I need to sort events by date:

(SELECT * from events_table ORDER BY date DESC)

But if I have more then 1 events on similar date, sorting works wrong. I want to sort by date and by id, to view correct order(new events first).
I know that good practice is to use a timestamp, but since users can introduce information about event that was a day or two ago and this method not working in my case.

È stato utile?

Soluzione

If you want first descending order by date and then ascending order by id then use below-

SELECT * from events_table ORDER BY date DESC, id ASC;

If you want first descending order by date and then descending order by id then use below-

SELECT * from events_table ORDER BY date DESC, id Desc;

If if id is primary key and auto_increment then there is no need to use ordering on date as ordering on id will be enough and will be more optimized.

SELECT * from events_table ORDER BY id Desc;

Altri suggerimenti

You can ORDER BY multiple fields.

SELECT * from events_table ORDER BY date DESC, id;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top