MYSQL check difference between dates and update table acordingly - mysql

I want to apply update to a table row through mysql prepared statement based on time difference between column installed and actual time DATEDIFF.
Here is my update and insert statement:
CREATE TABLE `installs` (
`idinstalls` int(11) NOT NULL AUTO_INCREMENT,
`key` varchar(45) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`DateTime` varchar(255) DEFAULT NULL,
`channelpref` varchar(255) DEFAULT NULL,
`contractorid` varchar(45) DEFAULT NULL,
`additiona` varchar(255) DEFAULT NULL,
`mail` varchar(255) DEFAULT NULL,
`installed` varchar(255) DEFAULT NULL,
`version` varchar(45) DEFAULT NULL,
`process` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idinstalls`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;
INSERT INTO `installs` VALUES (1,'1478997547716','Test instalation 1','2016-12-05 10:47:21',NULL,NULL,'Test',NULL,'2016-11-13 01:39:07',NULL,''),(2,'1478997633546','Tomo','2017-01-24 16:05:10',NULL,NULL,'Test',NULL,'2016-11-13 01:40:33',NULL,''),(3,'1479003293243','Test instalation 2','2017-01-24 04:26:49',NULL,NULL,'Test',NULL,'2016-11-13 03:14:53',NULL,''),(4,'1479118582052','Beta','2016-11-21 19:40:10',NULL,NULL,'Test','','2016-11-14 11:16:22',NULL,''),(5,'1479124220728','Beta 2','2017-01-22 15:54:41',NULL,NULL,'Test','','2016-11-14 12:50:20',NULL,''),(14,'1480154887591','','2016-11-26 12:41:01',NULL,NULL,NULL,NULL,'2016-11-26 11:08:07',NULL,''),(17,'1483456759196','','2017-01-13 11:42:06',NULL,NULL,NULL,NULL,'2017-01-03 16:19:20',NULL,''),(18,'1484474379679','','2017-01-24 12:12:41',NULL,NULL,NULL,NULL,'2017-01-15 10:59:41',NULL,'')
The columns that are relevant to this question are: key,name,installed and process.
Query should update column process based on these requisites:
If column name has a input (it is not null nor empty field) column process should be assigned value '1'.
If column name does not have input, query should check difference between 2 dates, first one is date and time that is in column installed for that row and other is actual current date and time, if datetime difference is greater than 30 days it should update column process for that row to a value '0'.
This is my Fiddle

You should use the datatype timestamp for columns DateTime and installed. Then you may do the following.
update installs set process = '1' where name is not null and name != '';
update installs set process = '0' where (name is null or name = '') and datediff(now(), installed) > 30;

If I was asking the question, I'd formulate the data set this way, and construct my question accordingly...
CREATE TABLE `installs` (
`idinstalls` int(11) NOT NULL AUTO_INCREMENT,
`key` varchar(45) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`installed` varchar(255) DEFAULT NULL,
PRIMARY KEY (`idinstalls`)
);
INSERT INTO `installs` VALUES
( 1,'16','Test instalation 1','2016-11-13 01:39:07'),
( 2,'46','Tomo' ,'2016-11-13 01:40:33'),
( 3,'43','Test instalation 2','2016-11-13 03:14:53'),
( 4,'52','Beta' ,'2016-11-14 11:16:22'),
( 5,'28','Beta 2' ,'2016-11-14 12:50:20'),
(14,'91','' ,'2016-11-26 11:08:07'),
(17,'96','' ,'2017-01-03 16:19:20'),
(18,'79','' ,'2017-01-15 10:59:41');

Related

Create trigger and stored procedure that updates Datetime when user is authenticated

I created a Login System in PHP and MySQL and I have the following table for the users:
CREATE TABLE `users` (
`ID` int(11) NOT NULL,
`Authenticated` tinyint(1) NOT NULL DEFAULT 0,
`Name` varchar(20) NOT NULL,
`Surname` varchar(20) NOT NULL,
`Username` varchar(20) NOT NULL,
`Email` varchar(255) NOT NULL,
`Password` varchar(70) NOT NULL,
`Created_At` datetime DEFAULT current_timestamp(),
`Authenticated_At` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
When the user signs up, a user is inserted in the table users with Authenticated = 0. I, as the admin, have to authenticate the user using:
UPDATE users SET Authenticated = 1 WHERE ID = {$id};
What I'd like to know is how to create a trigger and a stored procedure that updates the Authenticated_At column to the current Date and Time after the aforementioned UPDATE query.
Thanks in advance.
1) The simplest possible solution :
UPDATE users SET Authenticated = 1, Authenticated_At = NOW() WHERE ID = {$id};
2) Another solution is to set a DEFAULT value for the timestamp value. This is implemented in the table definition, like :
CREATE TABLE `users` (
`ID` int(11) NOT NULL,
`Authenticated` tinyint(1) NOT NULL DEFAULT 0,
`Name` varchar(20) NOT NULL,
`Surname` varchar(20) NOT NULL,
`Username` varchar(20) NOT NULL,
`Email` varchar(255) NOT NULL,
`Password` varchar(70) NOT NULL,
`Created_At` datetime DEFAULT current_timestamp(),
`Authenticated_At` datetime DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
From the documentation :
An auto-updated column is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. An auto-updated column remains unchanged if all other columns are set to their current values. To prevent an auto-updated column from updating when other columns change, explicitly set it to its current value. To update an auto-updated column even when other columns do not change, explicitly set it to the value it should have (for example, set it to CURRENT_TIMESTAMP).
In order for the Authenticated_At timestamp to be automatically updated every time the record is updated (while not updating Created_At), you want :
UPDATE users SET Authenticated = 1, Created_At = Created_At WHERE ID = {$id};
3) As wisely commented by #Raymond Nijland, the best solution is to define the timestamp column to be autoupdated only on UPDATE operations, like :
`Authenticated_At` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Pull records on or before 2 given dates

I was asked to pull records from Match table from 2 Given dates.
Say 2013/01/01 and 2013/02/29.
For 1 Match there are many possible bets when relationship is applied.
Say for a Match that Started around 2013/01/05, the bets relating to it
are bets that was made on or before 2013/01/05
What's weird is my boss would like to get also the records before the Match Date occured. Coz I already made a page that allows him to view the bet of a certain match.
coz in the first place the page is a Match page, so the search should be within the Match data right?
My idea is use something like
SELECT * from betdb
WHERE DateTime <= '2013/01/01 00:00:00' AND DateTime <= '2013/02/29 23:59:00'
But it just yields only 1 record that has a Date
1931-01-29 00:00:00
which was possibly typo error.
Is there a better way on pulling those kind of records that occured before the supplied DateTime?
Match table definition
CREATE TABLE IF NOT EXISTS `matchdb` (
`MatchID` int(11) NOT NULL AUTO_INCREMENT,
`BookID` int(11) NOT NULL,
`Category` varchar(40) NOT NULL,
`MatchName` varchar(60) NOT NULL,
`StartTime` datetime NOT NULL,
`Result1` varchar(20) DEFAULT NULL,
`Result2` varchar(20) DEFAULT NULL,
`Result3` varchar(20) DEFAULT NULL,
PRIMARY KEY (`MatchID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
Bet table definition
CREATE TABLE IF NOT EXISTS `betdb` (
`BetID` int(11) NOT NULL,
`BookID` int(10) NOT NULL,
`PlayerID` int(10) NOT NULL,
`DateTime` datetime NOT NULL,
`MatchID` int(10) NOT NULL,
`BetType` varchar(40) NOT NULL,
`Bet` varchar(40) NOT NULL,
`BetAmount` float NOT NULL,
`Odds` float NOT NULL,
`BetResult` varchar(40) NOT NULL,
`Payout` float NOT NULL,
PRIMARY KEY (`BetID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1;

MySQL query issue with combining two tables

I have two tables:
`search_chat` (
`pubchatid` varchar(255) NOT NULL,
`profile` varchar(255) DEFAULT NULL,
`prefs` varchar(255) DEFAULT NULL,
`init` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`session` varchar(255) DEFAULT NULL,
`device` varchar(255) DEFAULT NULL,
`uid` int(10) DEFAULT NULL,
PRIMARY KEY (`pubchatid`)
and
`chats` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`chatlog` varchar(255) DEFAULT NULL,
`block` varchar(2) DEFAULT '',
`whenadded` datetime DEFAULT NULL,
`pubchatid1` varchar(255) DEFAULT NULL,
`pubchatid2` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
So basically people chat with each other through a search system based on prefrences. The further they are apart, the worse it is. So the query I have is simple:
SELECT *
FROM search_chat
WHERE levenshtein(profile, "[user_prefs]") < 20
AND pubchatid <> "[user_pubchatid]"
ORDER BY
levenshtein(profile, "[user_prefs]")
LIMIT 1
It is a shitty query in itself, but it does the job (everything between "[]" is a variable I put in, just to make it clear).
As you can see this query only makes a selection between two peoples preferences (prefs) and how they are (profile). So far so good.
I have been bugging around some to make this query also check if they have had previous chats. That is where "chats" comes in. I can not get the query to check for a proper user and see if they have an open chat.
In chats, the "search_chat.pubchatid" can be either "chats.pubchatid1" or "chats.pubchatid2"
So somehow I have got to make these two work, making chats rule out options in search_chat.
Do you want something like this:
-- ... ( start of query as per your question )
and not exists (
select *
from chats
where ( ( chats.pubchatid1 = search_chat.pubchatid )
or ( chats.pubchatid2 = search_chat.pubchatid ) )
and -- ... add any restriction on how recent the chat was
)

Accidentally specified weird sql query. What happened?

I ran this sql query in my database:
update payments set method = 'paysafecard' AND amount = 25 WHERE payment_id IN (1,2,3,4,5,...)
Of course i meant set method = 'paysafecard' , amount = 25
However I did it in phpmyadmin and it showed me that rows were affected. After running it again it showed 0 rows affected.
I don't know what may have changed in the database, what could this have done?
My table looks like this:
CREATE TABLE IF NOT EXISTS `payments` (
`payment_id` int(11) NOT NULL AUTO_INCREMENT,
`method_unique_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`method` enum('moneybookers','paypal','admin','wallet','voucher','sofortueberweisung','bitcoin','paysafecard','paymentwall') COLLATE utf8_unicode_ci NOT NULL,
`method_tid` int(11) DEFAULT NULL,
`uid` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`plan` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`expires_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`amount` decimal(8,2) NOT NULL,
`currency` enum('EUR','USD','BTC') COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`payment_id`),
UNIQUE KEY `method` (`method`,`method_tid`),
UNIQUE KEY `method_unique_id` (`method_unique_id`,`method`),
KEY `expires_at` (`expires_at`),
KEY `uid` (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=8030 ;
I am running
-- Server version: 5.1.41
-- PHP Version: 5.3.2-1ubuntu4.11
This would result in the method field being set to '0' for all of your records fitting the where clause.
It is interpreted as the following:
set method = ('paysafecard' AND amount = 25)
This is a logical AND, and results in a boolean value for these records(which will be parsed to the corresponding field of your column).

Updating TimeStamp field a Slow Query in MySQL

My Table structure
CREATE TABLE IF NOT EXISTS `login` (
`eMail` varchar(50) NOT NULL,
`Password` tinytext NOT NULL,
`UID` int(9) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(16) NOT NULL,
`Text` tinytext NOT NULL,
`OldText` tinytext NOT NULL,
`LastSeen` timestamp NULL DEFAULT NULL,
`SecurityQuestion` tinytext NOT NULL,
`SecurityAnswer` tinytext NOT NULL,
PRIMARY KEY (`UID`),
UNIQUE KEY `eMail` (`eMail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
When ever i try to update the LastSeen it shows as slow query [get logged into the slow query log file]
Can someone tell me whats wrong ?
A Sample SQL code [PHP]
$time = date("Y-m-d H:i:s");
UPDATE LOGIN set LastSeen=? WHERE UID=?
mysqli_stmt_bind_param($stmt,"si",$time,$uid);
Edit:
I need the Timestamp cause i want to subtract current time with the data from the row. By default Timestam is automatically updated on each update, but it can be changed though [in my table the LastSeen filed is not automatically updated].
You shouldn't be updating a timestamp column: timestamp columns are automatically updated to the current time whenever you update the row.
If you want an updatable "timestamp" column in mysql, use the datetime datatype.