情景就是这样。我有table1副本到table2。我每次重新加载浏览器时都会删除重复的数据,但我遇到的问题是如果我编辑table1数据,我不希望它覆盖table2中的现有记录。 我怎么做? 我从table1
更新任何数据后,一直收到此错误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'
答案 0 :(得分:1)
您可以使用此查询:
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 |
+----+--------+--------+