I am using MySql via terminal. Below is the command I have used to create table but it is showing date in YYYY-MM-DD HH:MM:SS (example: 2018-05-25 14:12:47)
create table test (foo int, ts timestamp default CURRENT_TIMESTAMP);
But I want by default it take yesterday date every time I insert data in (YYYY-MM-DD) format.
Please help me to find the command.
Thanks,
Amit
According to the official MySQL documentation https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add, you can do like this:
If you want to store the "yesterday" on creation:
ts TIMESTAMP NOT NULL DEFAULT NOW() - INTERVAL 1 DAY
If you want to store the "yesterday" on every update:
ts TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW() - INTERVAL 1 DAY
According to this answer Select records from NOW() -1 Day:
NOW() returns a DATETIME.
And INTERVAL works as named, e.g. INTERVAL 1 DAY = 24 hours.
So if your script is cron'd to run at 03:00, it will miss the first
three hours of records from the 'oldest' day.
To get the whole day use CURDATE() - INTERVAL 1 DAY. This will get
back to the beginning of the previous day regardless of when the
script is run.
Hope it helps!
DEFAULT values in MySQL must be constants. They can't be functions or expressions (with the exception of CURRENT_TIMESTAMP).
Source: http://dev.mysql.com/doc/refman/5.6/en/data-type-defaults.html
In addition you can add a trigger to your table for your requirement
Simply Create a Table without constraint
create table test (foo int, ts timestamp );
Then add a trigger to this table
CREATE TRIGGER settime
BEFORE INSERT on test
FOR EACH ROW BEGIN
IF new.`ts ` is null THEN
SET new.`ts ` = DATE_ADD(NOW(), INTERVAL -1 DAY);
END IF;
END;
Related
i looking for some help about MySQL, Very easy question, but really breaked my brain for some time.
i have a table called "logs", That have "date" thing, That is INT(11) of Timestamp, So, it use timestamp actual for it.
i gonna make a script that execute a SQL command each minute, That Check ALL rows, if "date" have more/equal than 6 hours, i tired so much, and nothing for help.
Some commands i used and won't worked.
DELETE FROM logs WHERE date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 6 HOUR));
DELETE FROM logs WHERE date < NOW() - INTERVAL 6 HOUR;
Won't help, So, i asking here if you can help me, Thanks.
You can do something like that :
DELETE FROM logs
WHERE FROM_UNIXTIME(date) < UNIX_TIMESTAMP(NOW() - INTERVAL 6 HOUR);
The date "thing" is called a column. The column has a specific datatype. The question indicates that the column is datatype INT(11). And in that column is stored unix-style 32-bit integer number of seconds since 1970-01-01 UTC.
If that's all true, then the first query form is appropriate. The expression on the right side (of the less than comparison) returns an integer number of seconds.
As a demonstration, consider this expression:
SELECT UNIX_TIMESTAMP( NOW() + INTERVAL -6 HOUR ) ==> 1528450555
or, the way the original is written
SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 6 HOUR))
returns an equivalent result.
The second query can be evaluated, but the automatic conversion from DATETIME to numeric will return us an integer value like 20180608153555 (i.e. yyyymmddhhmmss), not number of seconds since the beginning of the epoch.
Consider a demonstration, DATETIME dataytpe evaluated in numeric context:
SELECT NOW() + INTERVAL -6 HOUR + 0 ==> 20180608153600
If we use that expression, compare that to an INT(11) column, and delete all rows that have an INT(11) column less than that value, it's going to delete every row in the table that has a non-NULL value in that column.
Your date column must be of Type TIMESTAMP and not INT in order to be able compare timestamps with each other properly, or you can write:
DELETE FROM logs WHERE FROM_UNIXTIME(date) < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 6 HOUR));
I have a database with timestamp field which takes current timestamp by default, but I have problem with the time, like if I insert the row at 9:00 it will take 8 as timestamp.
So my question is how to make current_timestamp in that table add one hour by default? I know you can do it with php but I prefer pure mysql solution.
I have a problem with the server timezone but I don't want to change it, since I am afraid this might affect other databases on server, while I want to change timestamp only in one database.
Simply you cannot do CURRENT_TIMESTAMP + INTERVAL 1 HOUR, but you can define a trigger instead:
CREATE TRIGGER tr_dt_table BEFORE INSERT ON your_table FOR EACH ROW BEGIN
SET NEW.datetime_field = NOW() + INTERVAL 1 HOUR;
END
And remove any default values of that field (i.e. make it NULL by default) in order to avoid contradictions.
insert into table_name values (DATE_ADD(now() , INTERVAL 1 HOUR));
I am trying to create a query that will limit insertion into a table based on the last time the poster sent data to the table.
For example if you posted data to the table then you are locked out of the system for another 10 hours. Here is what I came up with so far. But I get nowhere with the actual results on the data. Any help?
SELECT DATE( `date` )
FROM tablename
WHERE DATE( CURDATE( ) ) < CURDATE( ) - INTERVAL 1002
DAY
LIMIT 0 , 30
This will return a single post from the last 10 hours, if it exists:
SELECT *
FROM tablename
WHERE `date` >= NOW() - INTERVAL 10 HOUR
LIMIT 1
I'm assuming date is declared as DATETIME, since actual DATE does not contain the time part and hence is only day-accurate.
If date is an integer UNIX timestamp, use this:
SELECT *
FROM tablename
WHERE `date` >= UNIX_TIMESTAMP(NOW() - INTERVAL 10 HOUR)
LIMIT 1
There are a number of ways you could do this. Perhaps if you have a user settings table you could simply add a "last_insert" field, and store the timestamp as an integer value- that would be a super simple way to do it- you could check the current timestamp vs user_settings.last_insert and voila!
I suppose you could use datetime too. Whatever floats the boat.
First of all, you need a DATETIME column and not a DATE column. Assuming that tablename.date is a DATETIME column, then 10 hours before right now is CURRENT_TIMESTAMP - INTERVAL 10 HOUR.
First of all create a Time (TIMESTAMP DEFAULT CURRENT_TIMESTAMP) columnt in your table. It will be automatically set to current date on row insert
Then check:
SELECT COUNT(*) FROM Table WHERE Time > NOW() - INTERVAL 10 HOUR
If its 1 or more - block
You must compare the time last post was put with current time, not current time with current time :|
I want to delete some messages from my MySQL database after 7 days.
My message table rows have this format:
id | message | date
The date is a timestamp in the normal format; 2012-12-29 17:14:53
I was thinking that an MySQL event would be the way to go instead of a cron job.
I have what I guess is a simple question to an experienced SQL person, how do I code the delete messages portion in brackets below?
An example would be appreciated, Thanks.
DELIMITER $$
CREATE EVENT delete_event
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
ON COMPLETION PRESERVE
DO
BEGIN
DELETE messages WHERE date >= (the current date - 7 days);
END;
$$;
You can try using this condition:
WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY)
So that the whole SQL script looks like this:
CREATE EVENT delete_event
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
ON COMPLETION PRESERVE
DO BEGIN
DELETE messages WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY);
END;
However, on your place I would solve the given problem with a simple cron script. The reasons to do this is simple: it's easier to maintain the code, no ugly SQL workarounds, integrates smoothly with your system.
This should do the trick.
DELETE FROM messages WHERE date < (CURDATE() - INTERVAL 7 DAY);
For those out there who are on a shared hosting, like 1and1's, and can't create events, an alternative is to use webcron
You just need to tell webcron the url of the php script you'd like to be run, and they'll trigger it for you at the intervals you want
I hasn't been writing any MySql stored procedures before, so I don't know them at all. I have one database table which has some records in it. The main column is dateTime - when this record was saved in the database.
I have wrote the MySql stored procedure to select every record from the specified date:
CREATE PROCEDURE getMessages(IN dateFrom DATETIME)
SELECT * FROM EsbMessage WHERE dateTime <= dateFrom;
And this is the call:
CALL getMessages('2012-10-04 13:11:09');
This works correctly, it returns me the records from the specified date.
What I need to do is:
If the record is over one week old, I need to update the other
column.
If the record is over one year old, I need to delete that record.
I can easily do this programmatically, but in this case I have to do this using stored procedure.
So I'am thinking of something like this:
CREATE PROCEDURE updateMessages(IN dateFrom DATETIME)
BEGIN
SELECT * FROM EsbMessage WHERE dateTime <= dateFrom;
#for each message
#if the message is over one week old but not over one year old:
UPDATE EsbMessage SET body = '';
#if message is over one year old:
DELETE FROM EsbMessage WHERE dateTime = #message.dateTime
END
But I don't know how to use for loop in stored procedure, and how to write if statements depending on my requirements and the other thing I don't now how to count the dates in MySql. For e.g. If I have the current date then I need to subtract the 365 days from the current date.
Could somebody help me with this issue?
You wouldn't need a loop, just have your conditions in the WHERE clause:
#if the message is over one week old but not over one year old:
UPDATE EsbMessage SET body = ''
WHERE dateTime >= DATE_SUB(NOW(),INTERVAL 1 WEEK) AND dateTime <= DATE_SUB(NOW(),INTERVAL 1 YEAR);
#if message is over one year old:
DELETE FROM EsbMessage WHERE dateTime >= DATE_SUB(NOW(),INTERVAL 1 YEAR);
How to loop and to use if clauses is described here: http://www.mysqltutorial.org/stored-procedures-loop.aspx
I would do it without loops:
CREATE PROCEDURE updateMessages(IN dateFrom DATETIME)
BEGIN
UPDATE EsbMessage SET body = '' where dateTime <= dateFrom -(86400*7); //86400 = 1 day
#if message is over one year old:
DELETE FROM EsbMessage where dateTime <= dateFrom -(86400*365);
END