mysql查询只返回使用过去一段时间后添加的行

时间:2012-02-21 06:44:02

标签: php mysql syntax

如果我有一个具有TIMESTAMP列的表,并且我只想检索在$ time = strtotime(“now”)设置的php变量之后添加的行,那么我将如何格式化查询语法?

$ q =“SELECT * FROM webchat_lines WHERE author ='某人' * {介于$ time和CURRENT_TIMESTAMP之间} * ORDER BY id DESC LIMIT 20" ;

4 个答案:

答案 0 :(得分:1)

$ q =“SELECT * FROM webchat_lines WHERE author ='someone'AND timestamp_colum BETWEEN'$ time'AND CURRENT_TIMESTAMP”

http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between

答案 1 :(得分:1)

尝试:

$q = "SELECT *
      FROM webchat_lines
      WHERE author='someone'
        AND timestamp BETWEEN FROM_UNIXTIME($time) AND NOW()
      ORDER BY id DESC
      LIMIT 20";

这使用FROM_UNIXTIME($time)strtotime输出(1970-xx-xx等以来的秒数)转换为日期,以便将其与您的timestamp列进行比较。 NOW()CURRENT_TIMESTAMP()的别名。

答案 2 :(得分:0)

$q= "SELECT * FROM webchat_lines WHERE author = 'someone' AND timestamp between $time and NOW() ORDER BY id DESC LIMIT 20"

答案 3 :(得分:0)

到目前为止,其他答案都未提及需要将时间格式化为MYSQL。

将时间转换为MYSQL DATETIME字符串

$time = date_format(time(), 'Y-m-d H:i:s');

运行SQL

$q = "SELECT * FROM webchat_lines 
        WHERE author = 'someone' AND 
              timestamp BETWEEN '$time' AND NOW() 
        ORDER BY id DESC 
        LIMIT 20";

我们正在使用Between运算符:http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between 并使用日期格式:http://www.php.net/manual/en/datetime.format.php

mysql的日期格式为YYYY-MM-DD hh:mm:ss