Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

datetime - Select records from one week previous in mysql

I have data that has a date (Y-m-d H:i:s) column (the type is datetime). I'd like to select all records from 1 week before a date I enter (in the below example: 2011-09-17 00:00:00, but am having some trouble. Here's what I've got:

SELECT * FROM emails WHERE (DATE(date) = date_sub(date('2011-09-17 00:00:00'), 1 week))

What am I doing wrong? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you're missing INTERVAL at the front of 1 week:

SELECT *
FROM emails
WHERE (DATE(date) = date_sub(date('2011-09-17 00:00:00'), INTERVAL 1 week));

Here is a query that I ran that does work for the DATE_SUB() part:

SELECT *
FROM wp_posts
WHERE post_modified > DATE_SUB(CURDATE(), INTERVAL 4 WEEK);

You can use a negative value to go do a "N weeks before given date" query so something like this would work:

SELECT *
FROM wp_posts
WHERE post_modified > DATE_SUB(CURDATE(), INTERVAL -1 WEEK);

Or:

SELECT *
FROM emails
WHERE (DATE(date) = date_sub(date('2011-09-17 00:00:00'), INTERVAL -1 week))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...