創(chuàng)建我們的數(shù)據(jù)集
CREATE TABLE test_date (
id int(12) NOT NULL AUTO_INCREMENT,
create_date datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
添加數(shù)據(jù)
INSERT INTO test_date VALUES (‘1’, ‘2018-12-17 00:00:00’);
INSERT INTO test_date VALUES (‘2’, ‘2018-12-16 00:00:00’);
INSERT INTO test_date VALUES (‘3’, ‘2018-12-15 00:00:00’);
INSERT INTO test_date VALUES (‘4’, ‘2018-12-14 00:00:00’);
INSERT INTO test_date VALUES (‘5’, ‘2018-12-13 00:00:00’);
INSERT INTO test_date VALUES (‘6’, ‘2018-12-12 00:00:00’);
INSERT INTO test_date VALUES (‘7’, ‘2018-12-11 00:00:00’);
INSERT INTO test_date VALUES (‘8’, ‘2018-12-10 00:00:00’);
INSERT INTO test_date VALUES (‘9’, ‘2018-12-09 00:00:00’);
INSERT INTO test_date VALUES (‘10’, ‘2018-12-08 00:00:00’);
INSERT INTO test_date VALUES (‘11’, ‘2018-12-07 00:00:00’);
INSERT INTO test_date VALUES (‘12’, ‘2018-12-06 00:00:00’);
INSERT INTO test_date VALUES (‘13’, ‘2018-12-05 00:00:00’);
INSERT INTO test_date VALUES (‘14’, ‘2018-12-04 00:00:00’);
2、查詢近七天的數(shù)據(jù):
SELECT * FROM test_date where DATE_SUB(CURDATE(), INTERVAL 6 DAY) <= create_date
DATE_SUB() 函數(shù)從日期減去指定的時間間隔宾抓。
DATE_SUB(date,INTERVAL expr type)碌更,6表示截取的天數(shù)裕偿,最后的DAY表示按天來進行截取。
CURDATE()表示當(dāng)前的系統(tǒng)時間(日期)痛单,另有CURTIME()表示當(dāng)前的系統(tǒng)時間(時分秒)嘿棘。
3、查詢近30天的數(shù)據(jù):
SELECT * FROM test_date where DATE_SUB(CURDATE(), INTERVAL 29 DAY) <= create_date;
4旭绒、查詢今天的數(shù)據(jù):
SELECT * FROM test_date where DATE_SUB(CURDATE(), INTERVAL 0 DAY) <= create_date