我需要从昨天和一周前存储的数据库中选择结果。我可以在同一个查询中执行此操作吗?
SELECT *
FROM t1
WHERE DATE(t1recordDate) = CURDATE() - INTERVAL 1 DAY
和
SELECT *
FROM t1
WHERE DATE(t1recordDate) = CURDATE() - INTERVAL 7 DAY
答案 0 :(得分:1)
您可以使用or
逻辑运算符,或者更好的是,使用速记in
:
SELECT *
FROM t1
WHERE DATE(t1recordDate) IN
(CURDATE() - INTERVAL 1 DAY, CURDATE() - INTERVAL 7 DAY)
答案 1 :(得分:1)
如果您只需要昨天和之前的值,而不是范围内的天数,则可以使用OR和date_sub
SELECT *
FROM t1
WHERE DATE(t1recordDate) = DATE(DATE_SUB(CURDATE(),INTERVAL 1 DAY))
OR DATE(t1recordDate) = DATE(DATE_SUB(CURDATE(),INTERVAL 7 DAY))
如果你需要所有范围
SELECT *
FROM t1
WHERE DATE(t1recordDate) BETWEEN DATE(DATE_SUB(CURDATE(),INTERVAL 7 DAY))
AND DATE(DATE_SUB(CURDATE(),INTERVAL 1 DAY))
答案 2 :(得分:0)
如果你不喜欢这个简单的解决方案,你可以试试这个:
select t1.*
from (
select
curdate() - interval 1 day as ts_from,
curdate() - interval 1 second as ts_to
union all
select
curdate() - interval 7 day as ts_from,
curdate() - interval 6 day - interval 1 second as ts_to
) as r
join t1 on t1.t1recordDate between r.ts_from and r.ts_to
http://rextester.com/PLVMY63927
它至少可以使用索引。