[英]How to ignore inserting records from a table to another table when both table field has same value in MySQL?
I have 2 tables which have names and emails. 我有2个表,其中包含姓名和电子邮件。 Now I want to merge these tables into a new table without duplicate records.
现在我想将这些表合并到一个没有重复记录的新表中。 I want to use email fields for avoiding duplicate values in both tables.
我想使用电子邮件字段来避免两个表中的重复值。 I heard INSERT IGNORE query is using for inserting values into a table without affecting existing records.
我听说INSERT IGNORE查询用于在不影响现有记录的情况下将值插入表中。 How to write INSERT IGNORE query to check email field for duplication checking.
如何编写INSERT IGNORE查询以检查电子邮件字段以进行复制检查。 If anyone knows other methods are also welcome.
如果有人知道其他方法也欢迎。
table1:
fid fname email
--- ----- -----
1 Balaji balaji@email.com
2 xxxxx xxxxx@email.com
3 Bala bala@email.com
table2:
gid gname gemail
--- ----- ------
1 Bala bala@email.com
2 vinoth vinoth@email.com
table3:
-------
id name email
-- ---- -----
1 Balaji balaji@email.com
2 xxxxx xxxxx@email.com
3 Bala bala@email.com
4 vinoth vinoth@email.com
MySQL support UPDATE ON DUPLICATE KEY
but in order to work, you need to add a unique
constraint on the table you want to insert. MySQL支持
UPDATE ON DUPLICATE KEY
但为了工作,您需要在要插入的表上添加unique
约束。
Assuming Table3
is the name of your new table. 假设
Table3
是新表的名称。 You need to add constraint first, 你需要先添加约束,
ALTER TABLE Table3 ADD CONSTRAINT tb_uq UNIQUE (name, email)
and you can now have unique records on the new table, to merge the previous table, 并且您现在可以在新表上拥有唯一记录,以合并上一个表,
INSERT INTO table3(name, email)
SELECT name, email
FROM
(
SELECT fid id, fname name, email FROM Table1
UNION ALL
SELECT gid id, gname name, gemail email FROM Table1
) s
ON DUPLICATE KEY UPDATE name = VALUES(name);
An alternative solution without using ON DUPLICATE KEY UPDATE
. 不使用
ON DUPLICATE KEY UPDATE
的替代解决方案。 is to use UNION
( without ALL ) and assumes that Table3.ID
is set as auto-increment 是使用
UNION
( 没有ALL )并假定Table3.ID
设置为自动增量
INSERT INTO table3(name, email)
SELECT name, email
FROM
(
SELECT fname name, email FROM Table1
UNION
SELECT gname name, gemail email FROM Table2
) s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.