dragon201401 2017-07-25 17:57
浏览 114
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • dqhbuwrwq692118284 2017-07-25 18:04
    关注
    $sql = "SELECT $rows FROM $table ORDER BY Date DESC, ID DESC";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么