简体   繁体   中英

How delete Mysql entry by timestamp?

I'm a Noob, finishing off a website that has a simple MySQL database, that contains reviews and dates. I want to be able to delete reviews by date. The date field info is Field = Date, Type = timestamp, Null = No, Default = Current_Timestamp and Extra = on update CURRENT TIMESTAMP. For display purposes, this worked great, as the page ended up with Review 1 - June 1, Review 2 - June 2, Review 3 - June 7 (date saved as 2019-06-07 03:16:18 in DB). So, I decided to get rid of my most recent review with the following line in terminal. To my surprise, it deleted my whole database. Is this because of the extra column. Simple answers that I can understand are preferred to clever ones I can't. I've read a bunch of pages (which is how I got the syntax) and several posts on here and still don't know either the correct syntax, or why I got the unexpected behavior.

DELETE FROM Posts where Date > 2019-06-06

Can you try enclosing the date in '' like '2019-06-06'. Also I believe you should be using timestamp format. In DB2 it is YYYY-MM-DD HH:MM:SS.uuuuuu but in MSSQL it is YYYY-MM-DD HH:MM:SS.uuu. Not sure what it is for mySql but can you try '2019-06-06 00:00:00.000' or '2019-06-06 00:00:00.000000'

Now if that works and since this is timestamp try to change the where clause to

Date BETWEEN '2019-06-06 00:00:00.000000' and '2019-06-06 00:00:00.000000' + INTERVAL 1 DAY. The point is 1 day is a time range.

DELETE FROM Posts where Date > "2019-06-06"

上面的命令将删除2019-06-06之后的所有帖子

Not trying to be clever, but I would consider deleting last row by auto increment ID rather than date. Deleting using > can get you in to trouble.

Maybe something like

DELETE FROM table ORDER BY id DESC LIMIT 1

My simple table ("Posts") basically contains reviews and dates. To safely delete entries between May 20, 2019 and June 1, 2019 (ie without affecting reviews from the 20th or the 1st), I do the following in MySQL:

1) Check to see I'm getting the right entries: SELECT * FROM Posts WHERE Date < '2019-06-01 00:00:00.000000' AND Date > 2019-05-21 00:00:00 000000'; (this returns all entries from the stroke of midnight on the 21st, so after the 20th)

2) DELETE FROM Posts WHERE Date > '2019-05-21 00:00:00.000000 AND DATE < '2019-06-01 00:00:00 000000';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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