mysql数据库中有这样一张表
table:(含有id time info三个字段)
id           time               info
1      2011-03-01 19:00:00       XX2      2011-03-01 17:00:00       AA3      2011-03-01 18:30:30       YY4      2011-03-01 18:30:00       ZZ想实现,首先按时间倒序排序,最近的时间放在最前面,然后,拍好序的结果,将每条记录的时间减去下条
记录的时间,求出时间差(用秒表示),作为新的结果字段difftime,排序后,想要实现结果如下:
id            time              info        difftime
1      2011-03-01 19:00:00       XX         18003      2011-03-01 18:30:30       YY         304      2011-03-01 18:30:00       ZZ         54002      2011-03-01 17:00:00       AA         0请问在php里用什么样的sql语句能实现?

解决方案 »

  1.   

    select *, UNIX_TIMESTAMP(time)-(select min(UNIX_TIMESTAMP(time)) from 这样一张表 where time>a.time) as difftime
    from 这样一张表 a
    order by time
      

  2.   

    不太理解where time>a.time这句的意思,不明嵌套的子查询如何调用外部的time值,还请解释下,这里的time和a.time,那个是内部的,那个是外部的啊
      

  3.   

    我实际上是这样写的:
    select *, (UNIX_TIMESTAMP(time)-(select max(UNIX_TIMESTAMP(time)) from table where time>a.time)) as difftime from table 
    order by time desc但是还是老提示说语法错误,不知道怎么回事?
      

  4.   

    time 内部的
    a.time 外部
      

  5.   

    我这样写的,怎么老报错误,就是as那个地方,究竟哪里错了啊?select *, (UNIX_TIMESTAMP(time)-(select max(UNIX_TIMESTAMP(time)) from table where time<table.time)) as difftime from table 
    order by time desc
      

  6.   


    select *, UNIX_TIMESTAMP(time)-(select max(UNIX_TIMESTAMP(time)) from table where time<table.time) as difftime from table 
    order by time desc我按上面的写了,不报错了,但是里面的查询:select max(UNIX_TIMESTAMP(time)) from table where time<table.time总是不能正确给出结果,如果time<table.time这里,我把table.time换成一个具体的时间值,就可以,但是这样就与初衷不符,想的是table.time应该是外部的那个time,怎么应用到内部查询中?
      

  7.   

    看您在1楼里写的,这样一张表和那样一张表,好想内部和外部的表还不一样呢,总共就一张表table,该怎么实现呢?上面的代码错在哪呢?请指教!
      

  8.   

    select *, UNIX_TIMESTAMP(time)-(select min(UNIX_TIMESTAMP(time)) from `table` where time>a.time) as difftime
    from `table` a
    order by time
      

  9.   

    非常强悍,谢谢!解决问题!我要按时间倒序排列,就这样实现了:select *, UNIX_TIMESTAMP(time)-(select max(UNIX_TIMESTAMP(time)) from `table` where time<a.time) as difftime
    from `table` a
    order by time desc关键是要给外层的表起个别名用以区分子查询的表名。再次谢谢ACMAIN_CHM,又学到东西了
      

  10.   

    为了感谢ACMAIN_CHM,将分加至100!