我偶然发现了一个我认为很容易解决的问题,但似乎让我抓狂。所以,我试图按时间对一些 MySQL 记录进行排序,然后按日期对它们进行“分组”。例如,这是我的 MySQL 数据:
+----+------------+----------+---------------------------+--------+
| id | date | time | entry | status |
+----+------------+----------+---------------------------+--------+
| 21 | 2011-10-05 | 09:42:06 | All systems online. | 1 |
| 22 | 2011-10-05 | 09:43:09 | Maintenance starting. | 2 |
| 23 | 2011-10-04 | 08:42:06 | Systems online and ready. | 1 |
| 24 | 2011-10-05 | 09:44:30 | Systems are offline. | 0 |
+----+------------+----------+---------------------------+--------+
因此,我用来对所有内容进行排序的查询是:
SELECT * FROM status order by date ASC;
产生以下结果:
+----+------------+----------+---------------------------+--------+
| id | date | time | entry | status |
+----+------------+----------+---------------------------+--------+
| 21 | 2011-10-05 | 09:42:06 | All systems online. | 1 |
| 22 | 2011-10-05 | 09:43:09 | Maintenance starting. | 2 |
| 24 | 2011-10-05 | 09:44:30 | Systems are offline. | 0 |
| 23 | 2011-10-04 | 08:42:06 | Systems online and ready. | 1 |
+----+------------+----------+---------------------------+--------+
PHP 输出是问题所在。所以,现在的输出是:
2011 年 10 月 4 日
- 系统在线并准备就绪。 [上午 8 点 42 分]
2011 年 10 月 5 日
所有系统在线。 [上午 9 点 42 分]
维护开始。 [上午 9 点 43 分]
系统处于离线状态。 [上午 9 点 44 分]
我想要的输出是什么:
2011 年 10 月 5 日 - 系统离线。 [09:44 AM]
维护开始。 [上午 9 点 43 分]
所有系统在线。 [上午 9 点 42 分]
2011 年 10 月 4 日
- 系统在线并准备就绪。 [上午 8 点 42 分]
基本上,我希望所有内容都按日期分组(最新的在前),并且我希望最近的时间位于顶部,而不是底部。
这是我的 PHP 代码:
function getUpdates() {
global $db;
$updchk = "";
$entries = $db->GetAll("SELECT * FROM status order by date DESC;");
if (!$entries) { ?>
<p>No entries in the database, yet.</p>
<?php } else
foreach ($entries as $entry) {
if (ConvertDate($entry['date']) != $updchk) { ?>
<h4><?php echo ConvertDate($entry['date']); ?></h4>
<p><?php echo $entry['entry']; ?><span class="timestamp"> [<?php echo strftime('%I:%M %p', strtotime($entry['time'])); ?>]</span></p>
<?php $updchk = ConvertDate($entry['date']); ?>
<?php } else { ?>
<p><?php echo $entry['entry']; ?><span class="timestamp"> [<?php echo strftime('%I:%M %p', strtotime($entry['time'])); ?>]</span></p>
<?php }
} ?>
<?php } ?>
感谢任何帮助。
谢谢!
最佳答案
只需在 ORDER BY 中添加一个额外的子句?
SELECT ...
FROM status
ORDER BY `date` DESC, `time` DESC
您可以根据需要对任意多个(或几个)字段进行排序,如果需要,甚至可以对任意表达式进行排序。
关于PHP/MySQL : Sort by time, 然后按日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7663539/