简体   繁体   English

MySQL:获取上次日期的记录

[英]Mysql: Get records from last date

I want to get all records which are not "older" than 20 days. 我想获取所有不早于20天的记录。 If there are no records within 20 days, I want all records from the most recent day. 如果20天内没有记录,我希望获得最近一天的所有记录。 I'm doing this: 我正在这样做:

SELECT COUNT(DISTINCT t.id) FROM t
WHERE 
(DATEDIFF(NOW(), t.created) <= 20 
OR 
(date(t.created) >= (SELECT max(date(created)) FROM t)));

This works so far, but it is awful slow. 到目前为止,它仍然有效,但是速度很慢。 created is a datetime, might be due tue the conversion to a date... Any ideas how to speed this up? 创建的是日期时间,可能是由于转换为日期而已...任何想法如何加快速度?

SELECT COUNT(*) FROM (
 SELECT * FROM t WHERE datediff(now(),created) between 0 and 20
 UNION 
 SELECT * FROM (SELECT * FROM t WHERE created<now() LIMIT 1) last1
) last20d

I used the between clause just in case there might be dates in the future in the table. 我使用了between子句,以防表中将来可能有日期。 These will be excluded. 这些将被排除。 Also you can simplify the select, if you just need the count() to 如果需要count()来简化选择,

SELECT COUNT(*) FROM (
 SELECT id FROM t WHERE datediff(now(),created) between 0 and 20
 UNION 
 SELECT id FROM (SELECT id FROM t WHERE created<now() LIMIT 1) last1
) last20d

otherwise, in the first select version you can leave out the outer select if you want all the data of the chosen records. 否则,在第一个选择版本中,如果要选择记录的所有数据,则可以省略外部选择。 The UNION will make sure that duplicates will be excluded (in other cases I always use UNION ALL since it is faster). UNION将确保排除重复项(在其他情况下,我总是使用UNION ALL因为它速度更快)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM