Insert timestamp into a database + 7 days - mysql

I am trying to create a table in MySQL that has a timestamp field that is 7 days ahead of now() is there a way to do this?
This is my current code
CREATE TABLE tbl_reg
(
reg_id int(7) NOT NULL auto_increment KEY,
user_id int(7) NOT NULL,
registration_key char(50) NOT NULL,
registration_expires timestamp default now()+7days,
stamp_created timestamp default now()
);
Can anyone help as i cant find anything like this on the mysql site and wondered if there was a way to do it?

There are a number of date/time functions in MySQL that will do the trick here.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
registration_expires=DATE_ADD(NOW(), INTERVAL 7 DAY)
You can't set an expression as a default, though - you'll need to do it in your INSERT queries. Notice that even if your expr value is > 1 there is no plural used for the unit value.

Or you could create a view from a query where you add the interval, or when you query the db always add the 7 days interval.

Related

optimizing query and table in mysql 5.1

I have a question regarding optimizing the following query/table
SELECT playitemid,MAX(playdatetime)
FROM buma
WHERE licenseid = 1 AND playdatetime > Date_sub(Curdate(), INTERVAL 1 month)
GROUP BY playitemid
For a table with 11 million records this can sometimes take over 30 seconds.
Here is the create statement for the table.
CREATE TABLE `buma` (
`bumaid` int(11) NOT NULL AUTO_INCREMENT,
`playitemid` int(11) NOT NULL,
`playdatetime` datetime DEFAULT NULL,
`stopdatetime` datetime DEFAULT NULL, `licenseid` int(11) NOT NULL, editionid` int(11) DEFAULT NULL,
PRIMARY KEY (`bumaid`),
KEY `ind_buma`(`playdatetime`,`licenseid`,`playitemid`) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=68644363 DEFAULT CHARSET=latin1;
Is there any way to define a better key or index to speed up the query
Kind regards,
Bjørn
Try to index only playdatetime, licenseid, playitemid alone or groupe only licenseid,playitemid.
MySQL 5.1 is very old (10 years old).
Upgrade to 5.7 for a good performance increase (or use a mysql fork like mariadb 10.1).
You can also try to calculate this : Date_sub(Curdate(), INTERVAL 1 month) without mysql (php strtotime or other), and use mysql cache for instant request if you call it more than one time per day, be carefull dont use more than 128MB, it can decrease performances too).

Storing time in MySQL

I have data in the format of both "2013-01-17 18:46:47 -0800" and "1358477089" ...I'm wondering what is the best way to store this in a mysql db, that allows me to select results within a certain month, week, day etc.. using mysql's own functions.
Currently my create table code is like this.. the "timestamp" needs changing.
visible
CREATE TABLE IF NOT EXISTS `votes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`from` varchar(32) NOT NULL,
`username` varchar(32) NOT NULL,
`address` varchar(16) NOT NULL,
`timestamp` varchar(32) NOT NULL,
PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Best way is to use MySQL built-in DATETIME type.
MySQL offers lots of function which will allow you to select results within a certain month, week, day, whatever you need.
See great list of functions here:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
As hek2mgl and other guys mentioned, there is also TIMESTAMP.
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)
If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored.
I preffer and advice you to use DATETIME.
If you use a timestamp your field should be an "integer" not a varchar. This provides better perfomance (for example if you use an index for this column).
If you do not need to have dates before 1970 I would suggest to use a timestamp, not a datetime. It is easier to use.
PHP
$timestamp = date('U');
MySQL
INSERT INTO table SET timestamp = UNIX_TIMESTAMP()

MySQL Query list

I'm going to try to explain this best I can I will provide more information if needed quickly.
I'm storing data for each hour in military time. I only need to store a days worth of data. My table structure is below
CREATE TABLE `onlinechart` (
`id` int(255) NOT NULL AUTO_INCREMENT,
`user` varchar(100) DEFAULT NULL,
`daytime` varchar(10) DEFAULT NULL,
`maxcount` smallint(20) DEFAULT NULL,
`lastupdate` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=innodb AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
The "user" column is unique to each user. So I will have list for each user.
The "daytime" column I'm having it store the day and hour together. So as for today and hour it would be "2116" so the day is 21 and the current hour is 16.
The "maxcount" column is what data for each hour. I'm tracking just one total number each hour.
The "lastupdate" column is just a timestamp im using to delete data that is 24 hours+ old.
I have the script running in PHP fine for the tracking. It keeps a total of 24 rows of data for each user and deletes anything older then 24hours. My problem is how would I go about a query that would start from the current hour/day and pull that past 24 hours maxcount and display them in order.
Thanks
You will run into an issue of handling this near the end of the year. It's advisable you switch to using the native timestamp type of MySQL (described here: http://dev.mysql.com/doc/refman/5.0/en/datetime.html). Then you can grab max count by doing something such as:
SELECT * FROM onlinechart WHERE daytime >= ? ORDER BY maxcount
The question mark should be replaced by the timestamp - 86400 (number of seconds in a day).

How to set default value to sysdate in MySql?

I am going to create a table with a column storing Created_date which is of datetime datatype. And my aim is to set its default value as sysdate().
I tried
CREATE TABLE tbl_table (
created_date datetime DEFAULT sysdate())
This gives me error saying not a valid default statement. I used similar logic in Oracle.
Please help me to resolve this.
Thanks in advance.
Try
CREATE TABLE tbl_table ( created_date TIMESTAMP DEFAULT NOW())
But: NOW is different from sysdate and TIMESTAMP is different from datetime, keep this in mind.
Normaly you only can use constants for default-values. TIMESTAMP is the only column-type which supports a function like NOW(). See here for further information on the MySQL Bugtracker.
CREATE TABLE tbl_table(
created_datetime DATETIME DEFAULT CURRENT_TIMESTAMP,
modified_datetime DATETIME ON UPDATE CURRENT_TIMESTAMP
)
Should do the trick.

Issue inserting timestamp value in MySQL

There are some other questions where people have problems with timestamp being all zeros. I have checked them and this is not a duplicate.
I declare a table like this:
CREATE TABLE `my_db`.`my_table` (
`time_stamp` timestamp NOT NULL,
`author` varchar() NOT NULL,
`text` text NOT NULL,
`md5` int(11) NOT NULL,
PRIMARY KEY (`time_stamp`)
) ;
I also have a second table which will have a timestamp as primary key and they should have the same value.
Coding in Delphi, I use SELECT CURRENT_TIMESTAMP which returns something like '19/6/2010 4:56:17 AM' which I then use in an INSERT statement. The INSERT succeeds, but the timestamp is all zeros.
What am I doing wrong?
Here's the INSERT code:
sqlCommand := 'INSERT INTO my_db.my_table(time_stamp, author, text, md5) VALUES ("'
+ timestamp +
'", "mawg", ' +
'"Hello, world"' +
0 +
'");';
Result := DoSQlCommandWithNoResultSet(sqlCommand, AdoConnection);
Insertion will be extremely low rate, one entry every few weeks or maybe months, so I am happy with timestamp as primary key. I am keeping "versions" of things, so timestamp makes sense to me.
I am begging to think that this is an ADO problem, although I would expect ADO to just "pass through". I don't see any other solution. In a console, the output is "correct", but when run through ADO in Delphi then it is wrong
Can I specify to MySQL how it ought to format its dates?
After reviewing the MySQL documentation, it appears that if your timestamp value is incorrectly formatted, it would normally cause the timestamp to be '0000-00-00 00:00:00'.
In any case, you don't need to specify a timestamp value—that's the benefit of TIMESTAMP over DATETIME. And even if you did, you can simply set it to NOW() instead of running an unnecessary SELECT statement.
Edit:
Also, I know you said you thought this through, but have you considered daylight savings time? This could cause two records to have the same timestamp when the clock is set back during autumn.
Edit 2:
K, I don't know why I didn't catch this earlier, but that timestamp format you gave is incorrect. Try inserting a valid timestamp like '2010/06/19 4:56:17'. MySQL has pretty relaxed parsing of date & time values, but it always has to be year-month-date and hour-minute-seconds.
Edit 3:
Alright, there seems to be a little confusion over this, so I'm gonna post this quote from the MySQL 5.0 doc page on the DATETIME format:
For values specified as strings that include date part delimiters, it is not necessary to specify two digits for month or day values that are less than 10. '1979-6-9' is the same as '1979-06-09'. Similarly, for values specified as strings that include time part delimiters, it is not necessary to specify two digits for hour, minute, or second values that are less than 10. '1979-10-30 1:2:3' is the same as '1979-10-30 01:02:03'.
Have a look at MySQL date functions. They are very extensive and allow a high flexibility.
Besides all that, I would recommend re-thinking your table structure. A timestap as a primary key is not exactly what you want. When you have high traffic, it CAN happen, that the timestamp is the same. Also if you are saving 2 or more records in a row, the timestamp will be the same. Furthermore, your MD5 column is set to int(11). MD5 hashes use mixed characters, so i would rather go with varchar(32).
CREATE TABLE `my_db`.`my_table` (
`id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL,
`author` varchar(100) NOT NULL,
`text` text NOT NULL,
`md5` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ;
AFAIR 19/6/2010 4:56:17 AM is not a valid date format for MySQL date types. You should convert it to 2010-06-19 04:56:14 (see doc).