什么是选择查询来搜索记录“上周”,“上个月”和“去年”?

时间:2011-11-14 10:19:53

标签: mysql sql sorting select

我有一个系统,我需要在其中显示记录列表,我们有三个选项

  1. 上周
  2. 上个月
  3. 去年
  4. 我的表格结构有一个字段调用createdate,它是BIGINT类型,并保存从PHP的time()函数中获取的数据。

    请指导我通过“上周”,“上个月”和“去年”获取选择查询以搜索记录

    由于

4 个答案:

答案 0 :(得分:3)

这应该可以解决问题:

SELECT * FROM my_table WHERE createdate BETWEEN DATE_SUB(NOW(), INTERVAL 1 week) AND NOW();    
SELECT * FROM my_table WHERE createdate BETWEEN DATE_SUB(NOW(), INTERVAL 1 month) AND NOW() ;   
SELECT * FROM my_table WHERE createdate BETWEEN DATE_SUB(NOW(), INTERVAL 1 year) AND NOW();

答案 1 :(得分:2)

许多给定的查询遭受索引的可用性差。如果您的createdate处于unix时间,则比较也应该在unix时间内进行。

SELECT *
    FROM mytable
    WHERE createdate
        BETWEEN UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY) AND UNIX_TIMESTAMP()

应提供在createdate上使用索引范围的方法,并且不需要全表扫描。

答案 2 :(得分:1)

SELECT * FROM mytable WHERE YEAR(FROM_UNIXTIME(createdate)) = YEAR(NOW())-1
SELECT * FROM mytable WHERE WEEK(FROM_UNIXTIME(createdate)) = WEEK(NOW())-1 AND YEAR(FROM_UNIXTIME(createdate)) = YEAR(NOW())
SELECT * FROM mytable WHERE MONTH(FROM_UNIXTIME(createdate)) = MONTH(NOW())-1 AND YEAR(FROM_UNIXTIME(createdate)) = YEAR(NOW())

有关选项,请参阅week function,例如一周的第一天。

答案 3 :(得分:1)

我认为它可能是这样的:

SELECT * FROM your_table
WHERE FROM_UNIXTIME(date_col) BETWEEN
    DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()

SELECT * FROM your_table
WHERE FROM_UNIXTIME(date_col) BETWEEN
    DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW()


SELECT * FROM your_table
WHERE FROM_UNIXTIME(date_col) BETWEEN
    DATE_SUB(NOW(), INTERVAL 1 YEAR) AND NOW()