我想返回在当前日期的最近7天内添加到数据库的所有记录。
我有活动日历表,如下所示
CREATE TABLE events_calender (
company_name varchar(30) DEFAULT NULL,
reg_date timestamp
);
我已将事件插入下个月,如下所示
Insert into events_calender values('Childerse Event' , '2013-10-24 18:19:03');
Insert into events_calender values('Womens Event' , '2013-10-27 18:19:03');
Insert into events_calender values('Mens Event' , '2013-10-30 18:19:03');
Insert into events_calender values('DOlls Event' , '2013-11-02 18:19:03');
我有一个网络服务,我需要提供本周的活动(从当前时间起7天)
我尝试过以下查询
SELECT * from events_calender
WHERE reg_date BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE()
但它没有给出任何结果。
请您告诉我导致错误的原因是什么?
http://sqlfiddle.com/#!9/d3d41/2
谢谢,祝周末愉快。
答案 0 :(得分:3)
试试这个:use DATE_ADD
首先更新数据,即with the 7 day range data
。然后使用下面的sql
,它应返回少量记录。
CREATE TABLE events_calender (
company_name varchar(30) DEFAULT NULL,
reg_date timestamp
);
Insert into events_calender values('Childerse Event' , '2015-10-24 18:19:03');
Insert into events_calender values('Womens Event' , '2015-10-21 18:19:03');
Insert into events_calender values('Mens Event' , '2015-10-27 18:19:03');
Insert into events_calender values('DOlls Event' , '2015-11-29 18:19:03');
<强> SQL:强>
SELECT * from events_calender
WHERE reg_date BETWEEN DATE( NOW() ) AND DATE( DATE_ADD( NOW() , INTERVAL 7 DAY ) )
答案 1 :(得分:1)
您的查询正确但插入命令有问题。您输入的日期时间错误,表示这些日期之间不存在数据。
Insert into events_calender values('Childerse Event' , '2015-10-23 12:00:00');
Insert into events_calender values('Womens Event' , '2015-10-22 12:00:00');
Insert into events_calender values('Mens Event' , '2015-10-21 12:00:00');
Insert into events_calender values('DOlls Event' , '2015-10-17 12:00:00');