2011-10-05 168 views
5

我偶然发现了一个我认为很容易解决的问题,但似乎让我发疯。所以,我试图按时间对一些MySQL记录进行排序,然后按日期对它们进行排序。例如,这里是我的MySQL数据:PHP/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日

  • 所有系统联机。 [09:42 AM]

  • 维护开始。 [09:43 AM]

  • 系统处于脱机状态。 [上午09点44分]

我想要的输出是:

2011年10月5日 - 系统处于脱机状态。 [09:44 AM]

  • 维护开始。 [09:43 AM]

  • 所有系统在线。 [上午09时42分]

2011年10月4日

  • 系统联机并准备就绪。 [08:42 AM]

基本上,我想按日期分组的所有东西(最新的第一个),我希望最近的时间在顶部,而不是底部。

这是我的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 } ?> 

任何帮助表示赞赏。

谢谢!

回答

18

只需在ORDER BY中添加一个额外的子句?

SELECT ... 
FROM status 
ORDER BY `date` DESC, `time` DESC 

你可以尽可能多(或几个)字段进行排序的,只要你想,即使是在任意表达式如果需要的话。

+0

哇工作,这很简单。 – drewrockshard

+1

+1为您的速度! ;) – JellyBelly

4

改变您的查询

SELECT * 
FROM status 
order by `date` desc, `time` desc; 
3

按日期,然后在SQL时间顺序,

SELECT * FROM status ORDER BY date DESC, time DESC; 
3

试试这个:按日期

SELECT * FROM `status` ORDER BY `date`, `time` DESC 
0

SELECT * FROM状态顺序(日期)asc,time desc;

1
SELECT * FROM `status` ORDER BY `date` DESC, `time` DESC 

会为你的代码

+3

请告诉我们,你的答案和已经接受的答案之间的区别,正确的答案,**张贴的年代AGO **! – Wh1T3h4Ck5