我偶然发现了一个我认为很容易解决的问题,但似乎要把我逼疯了。因此,我试图按时间对一些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 |
+----+------------+----------+---------------------------+--------+输出是问题所在。所以,现在的输出是:
2011年10月4日
2011年10月5日
我希望输出是什么:
2011年10月5日,-系统离线。上午9时44分
2011年10月4日
基本上,我想要按日期分组的所有东西(最新的第一次),我想要的是最近的时间在顶部,而不是底部。
以下是我的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 } ?>任何帮助都是非常感谢的。
谢谢!
发布于 2011-10-05 15:14:13
在订单上加一个额外的条款?
SELECT ...
FROM status
ORDER BY `date` DESC, `time` DESC您可以在任意多(或少数)字段上排序,即使是在任意表达式上(如果需要的话)。
发布于 2011-10-05 15:14:41
将查询更改为
SELECT *
FROM status
order by `date` desc, `time` desc;发布于 2011-10-05 15:15:27
若要按日期在SQL中按时间订购,请执行以下操作:
SELECT * FROM status ORDER BY date DESC, time DESC;https://stackoverflow.com/questions/7663539
复制相似问题