简体   繁体   English

MySQLi + PHP按日期和ID降序排列

[英]MySQLi + PHP sort by date and ID in descending order

I'm looking for a MySQL query that will sort the items by date in descending order. 我正在寻找一个MySQL查询,该查询将按日期降序对项目进行排序。 If it finds two or more rows with the same date, it will sort them by ID in descending order. 如果找到具有相同日期的两行或更多行,则将按ID降序对它们进行排序。

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. 它按日期降序显示项目,但是如果有两个具有相同日期的项目,则按ID升序而不是降序显示它们。

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. 我不想简单地按ID排序,因为有时我想添加过去发生的事件,这将需要我手动编辑该事件之后的所有事件的ID。

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. ID较高的那个几乎总是最后发生的那个。

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. 我可以按时间和日期排序,但是我没有关于过去事件的任何时间数据,因此我希望保持一致。

$sql = "SELECT $rows FROM $table ORDER BY Date DESC, ID DESC";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM