0

我有一个场景,我必须检查表中是否已经存在数据。如果用户 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);

此外,如果 int table1 的一行 temp_table 不存在,那么它的状态应该与我在所需输出中提到的 userdeleted 1 一样。

结果:表1

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

请帮忙

4

2 回答 2

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)
于 2013-06-17T13:42:38.230 回答
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 函数将从现有行创建一个新行...这样我可以同时比较多个字段,就好像我只比较一个字段一样...

不在”让您在查询中进行查询...

于 2013-06-17T11:58:10.623 回答