简体   繁体   English

mysql插入到另外的表中是否不存在

[英]mysql insert into if not exists from seperate table

I'm trying to insert an array of new contacts from a temporary import table into our primary customer database. 我正在尝试从临时导入表中向我们的主要客户数据库中插入一系列新联系人。 Before it is inserted, we want to first check if the contact exists on our blacklist. 在插入之前,我们要先检查联系人是否存在于我们的黑名单中。 If it does exists, we do not want to insert it into the primary table. 如果确实存在,我们不想将其插入主表。

I first pull the contacts from temp table: 我首先从临时表中提取联系人:

SELECT `email` FROM `import_contacts`

Then I want to insert those contacts into the primary table ONLY AFTER it has been "scrubbed" or checked against the blacklist. 然后,我只想将这些联系人“擦洗”或对照黑名单插入到主表中。 The way I have it currently: 我目前的方式:

INSERT INTO `contacts` (`email`) 
VALUES ('".implode("','','',''),('",$email)."','','','') 
WHERE...

I got confused when it occurred to me that imploding the array like I have implodes ALL contacts, including those on the blacklist. 当我想到像我已经爆破所有联系人(包括黑名单中的那些联系人)那样爆破数组时,我感到困惑。 So even if I were to get the WHERE statement to work, it would be wasteful and full of ambiguous data. 因此,即使我要使用WHERE语句,它也将是浪费的并且充满歧义的数据。

Is there a way to insert the contacts into the primary table after it has been checked against the blacklist table using one sql statement? 使用一个sql语句对照黑名单表检查联系人后,是否可以将联系人插入到主表中?

Any help would be greatly appreciated!! 任何帮助将不胜感激!!

INSERT INTO `contacts` (`email`)
SELECT email FROM `import_contacts`
WHERE `import_contacts.email` NOT_IN(`SELECT email FROM my_blacklist`);

Try using insert select from MySQL. 尝试从MySQL使用插入选择。

It will run a insert based on a select. 它将基于选择运行插入。

http://dev.mysql.com/doc/refman/5.1/en/insert-select.html http://dev.mysql.com/doc/refman/5.1/zh-CN/insert-select.html

Example from dev.mysql.com: 来自dev.mysql.com的示例:

INSERT INTO tbl_temp2 (fld_id)
  SELECT tbl_temp1.fld_order_id
  FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM