简体   繁体   English

日期间隔错误

[英]Date Interval Bug

I have a table which has a column called created DATETIME , When adding entries It works fine, but when It gets to Date Interval, It keeps on duplicating new entries. 我有一个表,该表的列称为created DATETIME ,当添加条目时,它可以正常工作,但是当达到Date Interval时,它将继续复制新条目。 I'm trying to get Today's and Yesterday's entries. 我正在尝试获取今天和昨天的条目。 Today's works fine, but for Yesterday's, It also puts on Today's contents in query results which Is not what I want. 今天的工作正常,但对于昨天的工作,它也在查询结果中放入了今天的内容,这不是我想要的。

SELECT * FROM tab WHERE created > DATE_SUB(NOW(), INTERVAL $num DAY) ORDER BY created DESC LIMIT 9;

$num Is 1 for Today's entries, and It's 2 for Yesterday's. $num对于今天的条目为1,对于昨天的条目为2。 So basically an entry which Is created today, Is getting duplicated on Yesterday's query results. 因此,基本上,今天创建的条目在昨天的查询结果中得到重复。

You are getting the results you requested from the database. 您正在从数据库中获得所需的结果。 Namely any record that is greater than today minus however many days you put in. 也就是说,任何大于今天的记录减去您输入的天数。

The reason you get 0 records when you try @KenWhite's suggested of changing your > to = is because your field is DATETIME, so subtracting exactly 24 hours from NOW() yields the same exact time yesterday and you probably don't have a record that was written precisely at this time yesterday. 当您尝试@KenWhite的将>更改为=建议获得0条记录的原因是因为您的字段是DATETIME,所以从NOW()减去24小时得出的昨天的确切时间是相同的,并且您可能没有记录正是在昨天这个时间写的 Right? 对?

What you'll have to do is test for records between two dates to get you want. 您要做的就是测试两个日期之间的记录,以获取所需的信息。 Instead of NOW(), switch to CURDATE(), this way you can be assured you'll get every record for the datetime range you are looking for. 不必使用NOW(),而是切换到CURDATE(),这样就可以确保您会获得要查找的日期时间范围的每条记录。

SELECT *
FROM tab
WHERE 
  created BETWEEN DATE_SUB(CURDATE(), INTERVAL $num DAY) AND DATE_SUB(CURDATE(), INTERVAL $num - 1 DAY) 
ORDER BY created DESC LIMIT 9;

You can check out a SQLFiddle of this here: http://sqlfiddle.com/#!2/19d9b/12 您可以在此处查看SQLFiddle: http ://sqlfiddle.com/#!2 / 19d9b / 12

With datetime/timestamp values, similar to floats, always use ranges with closed beginnings and open endings. 与浮点数类似,使用datetime / timestamp值时,请始终使用开头和结尾均封闭的范围。 So use '>=' and '<'. 因此,请使用'> ='和'<'。

For example to use the data of a single day: 例如,使用一天的数据:

SELECT ... FROM tab 
WHERE created >= CURDATE() - INTERVAL @num:=? DAY
  AND created <  CURDATE() - INTERVAL @num    DAY + INTERVAL 1 DAY
ORDER BY created DESC
LIMIT 9
;

With MySQL, generally prefer the timestamp type over the datetime type, as datetime doesn't carry timezone information. 使用MySQL时,通常首选时间戳类型而不是日期时间类型,因为日期时间不包含时区信息。

Alternatives: 备择方案:

created_at timestamp NULL DEFAULT NULL COMMENT 'set by application',

created_at timestamp NOT NULL DEFAULT '1970-01-01 23:00:00' COMMENT 'set by application',

dbms_row_created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'set by DBMS',

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

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