hph+mysql怎樣讓時間按照目前時間來排序?該如何處理

來源:互聯網
上載者:User
hph+mysql怎樣讓時間按照目前時間來排序?
庫內如下內容:
+-----+-------+---------------------+
| gid | text | time |
+-----+-------+---------------------+
| 1 | 內容1 | 2012-03-09 14:30:28 |
| 2 | 內容2 | 2012-03-09 13:40:36 |
| 3 | 內容3 | 2012-03-09 14:50:43 |
| 4 | 內容4 | 2012-03-09 09:10:15 |
| 5 | 內容5 | 2012-03-09 15:21:22 |
| 6 | 內容6 | 2012-03-09 15:25:07 |
| 7 | 內容7 | 2012-03-09 16:21:43 |
| 8 | 內容8 | 2012-03-09 14:21:13 |
| 9 | 內容9 | 2012-03-09 12:21:55 |
+-----+-------+---------------------+

假如目前時間是 2012-03-09 14:10:05 就是互連網目前時間
我想要在這樣排序然後顯示出來
最頂上的是最接近於目前時間的.如果同一時間的按插入的先後順序
接下來的是 大於目前時間的,也就是時間還未到的 也是按插入先後順序
最下邊的是時間已經小於目前時間的,但是時間按大的排在小的上面

+-----+-------+---------------------+
| gid | text | time |
+-----+-------+---------------------+
| 8 | 內容8 | 2012-03-09 14:21:13 |
| 1 | 內容1 | 2012-03-09 14:30:28 |
| 3 | 內容3 | 2012-03-09 14:50:43 |
| 5 | 內容5 | 2012-03-09 15:21:22 |
| 6 | 內容6 | 2012-03-09 15:25:07 |
| 7 | 內容7 | 2012-03-09 16:21:43 |
| 2 | 內容2 | 2012-03-09 13:40:36 |
| 9 | 內容9 | 2012-03-09 12:21:55 |
| 4 | 內容4 | 2012-03-09 09:10:15 |
+-----+-------+---------------------+
在PHP裡應該怎麼寫$result=mysql_query()

------解決方案--------------------
實際上
set @tt='2012-03-09 14:10:05';
SELECT * FROM `times` order by t>@tt desc, if(t>@tt,[email protected], @tt-t)
是有問題的
雖然 if(t>@tt,[email protected], @tt-t) 與 abs([email protected]) 是等價的,但使用 abs([email protected]) 時並不能獲得正確的結果。由此可知 datetime 類型並不能直接參与數學運算
應寫作
set @tt='2012-03-09 14:10:05';
SELECT * FROM `times` order by t>@tt desc, abs(UNIX_TIMESTAMP(t)-UNIX_TIMESTAMP(@tt))

對於你的應用就是
$tt=date('Y-m-d H:i:s');
$result=mysql_query("SELECT * FROM mysf order by kfsj>'$tt' desc, abs(UNIX_TIMESTAMP(kfsj)-UNIX_TIMESTAMP('$tt'))");

時間常量要用引號括起

如果 $tt 總是取時間的當前值,那麼 $tt 可用 now() 代替
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.