MYSQL根据日期和更新表检查区别

时间:2017-01-24 16:25:09

标签: mysql

我想根据列installed与实际时间DATEDIFF之间的时差,通过mysql预编译语句将更新应用于表行。

这是我的更新和插入声明:

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,'')

与此问题相关的列包括:keynameinstalledprocess

查询应根据以下要求更新列过程:

如果列name有输入(它不是空字段也不是空字段),则应为列process指定值' 1'。 如果列name没有输入,则查询应检查2个日期之间的差异,第一个是该行installed列中的日期和时间,其他是实际当前日期和时间,如果日期时间差异超过30天时,应将该行的process列更新为值' 0'。

这是我的Fiddle

2 个答案:

答案 0 :(得分:0)

如果我问这个问题,我会以这种方式制定数据集,并相应地构建我的问题......

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');

答案 1 :(得分:0)

您应该使用DateTime和已安装列的数据类型时间戳。然后你可以做以下几点。

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;