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

标签 mysql sql

场景是这样的。我有表1复制到表2。每次重新加载浏览器时,我都会删除重复的数据,但我面临的问题是,如果我编辑 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'

最佳答案

您可以使用此查询:

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 |
+----+--------+--------+

关于mysql - 将表 1 复制到表 2,但如果表 1 发生更改,则不更新表 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50057142/

相关文章:

mysql - 附加到 JSON 字段的 MySQL 的 GoLang 查询

mysql - 哪个sql查询更快: multiple selects or join?

mysql - 如何最小化我的查询以加快我的 navicat 中的查询时间?

javascript - 合并多对一的对象列表

sql - 选择行或默认行

MySql 时间戳错误 : Data truncation: Incorrect datetime value

sql - 优化 SQL 查询以避免全表扫描

php - 从 MySQL 中获取长变量/数字和 'squashing'

sql - 在多个条件下返回左外连接中的最后一行

sql - Derby 支持表和列注释吗?