将表1复制到表2,但如果表1发生更改,则不更新表2

iszxjhcz  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(234)

情况是这样的。我把1号桌的副本给2号桌。每次重新加载浏览器时,我都会删除重复的数据,但我面临的问题是,如果编辑table1数据,我不希望它覆盖table2中的现有记录。我该怎么做?一旦我更新了表1中的任何数据,我就会一直收到这个错误

Error: 
INSERT INTO table3 (ID,user,name) 
SELECT a.ID,a.user,a.name 
FROM table1 a 
LEFT JOIN table3 b 
ON a.ID = b.ID 
AND a.user = b.user 
AND a.name = b.name 
WHERE b.ID IS NULLDuplicate entry '1' for key 'PRIMARY'
qmb5sa22

qmb5sa221#

您可以使用此查询:

insert into table2(id, user, name)
select a.id, a.user, a.name FROM table1 a
where a.id NOT in (select b.id FROM table2 b);

插图:

-- create table table1
create table table1(
id int primary key,
user varchar(20),
name varchar(20));

-- create table table2
create table table2(
id int primary key,
user varchar(20),
name varchar(20));

-- populate 2 rows in table1
insert into table1 values(1,'user-1','name-1');
insert into table1 values(2,'user-2','name-2');

select * from table1;
+----+--------+--------+
| id | user   | name   |
+----+--------+--------+
|  1 | user-1 | name-1 |
|  2 | user-2 | name-2 |
+----+--------+--------+

-- sync table2
insert into table2(id, user, name)
select a.id, a.user, a.name FROM table1 a
where a.id NOT in (select b.id FROM table2 b);

select * from table2;
+----+--------+--------+
| id | user   | name   |
+----+--------+--------+
|  1 | user-1 | name-1 |
|  2 | user-2 | name-2 |
+----+--------+--------+

-- Update an existing id, and add a new id in table1
update table1 set user='user-11' where id=1;
insert into table1 values(3,'user-3','name-3');

select * from table1;
+----+---------+--------+
| id | user    | name   |
+----+---------+--------+
|  1 | user-11 | name-1 |
|  2 | user-2  | name-2 |
|  3 | user-3  | name-3 |
+----+---------+--------+

-- sync table2
insert into table2(id, user, name)
select a.id, a.user, a.name FROM table1 a
where a.id NOT in (select b.id FROM table2 b);

-- row with existing id 1 is not affected, new row with id 3 gets added
select * from table2;
+----+--------+--------+
| id | user   | name   |
+----+--------+--------+
|  1 | user-1 | name-1 |
|  2 | user-2 | name-2 |
|  3 | user-3 | name-3 |
+----+--------+--------+

相关问题