-5

我想获取所有超过 60 天的记录。我有 create_date 列,请提出满足上述要求的查询

SELECT * FROM mytable WHERE create_date BETWEEN  DATE_SUB(NOW(), INTERVAL 60 DAY)  AND create_date >'60days'

收到我的询问

正确的查询是

SELECT * FROM mytable WHERE create_date < DATE_SUB(NOW(), INTERVAL 60 DAY);
4

2 回答 2

2

In SQL, expression

x BETWEEN a AND b

literally means

a <= x AND x <= b

If a > b, this will yield empty result no matter what.

In other words, order does matter - simply make sure that when using x BETWEEN a AND b then a must be <= b.

For you it means swap dates (and fix some other errors as well):

SELECT * FROM mytable
WHERE create_date BETWEEN '2011-10-14'
          AND NOW() - INTERVAL 60 DAY

UPDATE: One more note about using functions DATE_SUB() or DATE_ADD().

In general, if you need to compare dates in big table, you should avoid using these functions at all costs! Modern MySQL supports date arithmetic using standard + and - operators, so expression

DATE_SUB(create_date, INTERVAL 60 DAY)

is equivalent to

create_date - INTERVAL 60 DAY

Not only this is easier to read, but it also allows server to take advantage of possible index you created for create_date column. This speed-up cannot be applied to any function call like DATE_SUB() - MySQL does not support functional indexes.

于 2013-05-17T05:22:11.437 回答
0

尝试类似的东西

select * from tablename where datediff(now(), date) > 60

我假设date存储在名为 的列中date,您使用列名而不是date.

希望它有效。

于 2013-05-17T05:16:45.733 回答