Heim  >  Artikel  >  Backend-Entwicklung  >  hph+mysql怎样让时间按照当前时间来排序?该如何处理

hph+mysql怎样让时间按照当前时间来排序?该如何处理

WBOY
WBOYOriginal
2016-06-13 10:11:171077Durchsuche

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() 代替

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn