Reputation: 41
I'm looking for a MySQL query that will sort the items by date in descending order. If it finds two or more rows with the same date, it will sort them by ID in descending order.
This is my current code:
$sql = "SELECT $rows FROM $table ORDER BY Date DESC";
It displays the items in descending order by date but if there are two items with the same date, it displays them in ascending order by ID instead of descending.
Example:
Let's assume that this is a set of data:
ID - date - text
1 - 2017-01-01 - oldest
2 - 2017-01-02 - two
3 - 2017-01-03 - morning
4 - 2017-01-03 - afternoon
5 - 2017-01-04 - latest
The current code would list it as:
ID - date - text
5 - 2017-01-04 - latest
3 - 2017-01-03 - morning
4 - 2017-01-03 - afternoon
2 - 2017-01-02 - two
1 - 2017-01-01 - oldest
I want it to list it as this:
ID - date - text
5 - 2017-01-04 - latest
4 - 2017-01-03 - afternoon
3 - 2017-01-03 - morning
2 - 2017-01-02 - two
1 - 2017-01-01 - oldest
I don't want to simply sort by ID because sometimes I want to add events that happened in the past and this would require me to manually edit the ID of all events after that one.
Sorting simply by date does not consider two events that happen on the same day at different times. The one with a higher ID is almost always going to be the one that happened last.
I could sort by time and date potentially but I do not have any time data on past events and I want to keep it consistent.
Upvotes: 2
Views: 6038