比较表中的数据

时间:2013-06-17 11:14:41

标签: mysql mysql-workbench

我有一个场景,我必须检查表中是否已存在数据。如果用户n应用程序已经存在,那么我们不需要执行任何其他操作来执行插入。

CREATE TABLE `table1` (
  `ID` INT(11) NOT NULL AUTO_INCREMENT,
  `GroupName` VARCHAR(100) DEFAULT NULL,
  `UserName` VARCHAR(100) DEFAULT NULL,
  `ApplicationName` VARCHAR(100) DEFAULT NULL,
  `UserDeleted` BIT DEFAULT 0,
  PRIMARY KEY (`ID`)
)

CREATE TABLE `temp_table` (
  `ID` INT(11) NOT NULL AUTO_INCREMENT,
  `GroupName` VARCHAR(100) DEFAULT NULL,
  `UserName` VARCHAR(100) DEFAULT NULL,
  `ApplicationName` VARCHAR(100) DEFAULT NULL,
  PRIMARY KEY (`ID`)
)

table1是主表,而temp_table我必须从中执行比较。

示例日期脚本:

INSERT  INTO `table1`(`ID`,`GroupName`,`UserName`,`ApplicationName`,`userdeleted`) 
VALUES 
('MidasSQLUsers','Kevin Nikkhoo','MySql Application',0),
('MidasSQLUsers','adtest','MySql Application',0),
('Salesforce','Kevin Nikkhoo','Salesforce',0),
('Salesforce','devendra talmale','Salesforce',0);

INSERT  INTO `temp_table`(`ID`,`GroupName`,`UserName`,`ApplicationName`,`userdeleted`) 
VALUES 
('MidasSQLUsers','Kevin Nikkhoo','MySql Application',0),
('MidasSQLUsers','adtest','MySql Application',0),
('Salesforce','Kevin Nikkhoo','Salesforce',0),
('Salesforce','Kapil Singh','Salesforce',0);

如果table1中不存在一行temp_table,那么它的状态应该是我在所需输出中提到的用户删除1。

结果:table1

ID  GroupName   UserName    ApplicationName Deleted
1   MidasSQLUsers   Kevin Nikkhoo   MySql Application 0
2   MidasSQLUsers   adtest  MySql   ApplicationName   0
3   Salesforce  Kevin Nikkhoo   Salesforce    0
4   Salesforce  devendra talmale Salesforce   1
5   SalesForce  Kapil Singh Salesforce    0

请帮忙

2 个答案:

答案 0 :(得分:1)

这应该可以解决问题,更改concat中的任何内容,以符合您的规范。

首先进行一次更新以“删除”不在tempTable中的行:

   update table t1 set deleted = 'YES' 
    where concat( t1.groupName, t1.Username, t1.application) NOT IN 
    (select  concat( t2.groupName, t2.Username, t2.application) from tempTable t2);

第二:插入新记录

insert into table1 t1 (t1.groupName, t1.username, t1.application_name, t1.deleted)

(select t2.groupName, t2.Username, t2.application, t2.deleted from tempTable t2    
where concat(t2.userName, t2.application, t2.groupName, t2.deleted) **not in** 
    (select concat(t3.userName, t3.application, t3.groupName, t3.deleted) 
       from table1 t3)

concat function将从现有行中创建一个新行...这样我可以同时比较多个字段,就像我只比较一个...

"not in"让您在查询中进行查询...

答案 1 :(得分:1)

上述查询略有不同。

使用JOIN,如果你有userName,application和groupName字段的索引可能会更快

UPDATE table1 t1 
LEFT OUTER JOIN temp_table t2
ON t1.userName = t2.userName
AND t1.application = t2.application
AND t1.groupName = t2.groupName
SET t1.deleted = CASE WHEN t2.ID IS NULL THEN 1 ELSE 0 END  

正常插入

INSERT INTO table1 t1 (t1.groupName, t1.username, t1.application_name, t1.deleted)
(SELECT t2.groupName, t2.Username, t2.application, t2.deleted 
FROM tempTable t2    
LEFT OUTER JOIN table1 t3
ON t2.userName = t3.userName
AND t2.application = t3.application
AND t2.groupName = t3.groupName
WHERE t3.ID IS NULL)