[英]With MySQL, how do I insert into a table on condition that the value does not exist in another table?
I have a MySQL database and I would like to insert some values into one table, assuming that a particular value that I am inserting does not match a value in a different table. 我有一个MySQL数据库,我想在一个表中插入一些值,假设我插入的特定值与另一个表中的值不匹配。
Here is a simplified/example structure: 这是一个简化的/示例结构:
Table: invites
id : int (auto-increment index)
name : varchar
message : varchar
Table: donotinvite
name : varchar (index)
Is it possible to do a conditional insert of a 'name' and 'message' pair into the 'invites' table assuming the 'name' does not match any 'name' from the 'donotinvite' table with a single statement? 假设'name'与'donotinvite'表中的任何'name'与单个语句不匹配,是否可以在'invites'表中有条件地插入'name'和'message'对?
Something like this, perhaps? 也许是这样的事情?
INSERT INTO invites
SET name = 'joe', message = 'This is an invite'
WHERE NOT EXISTS
(SELECT name
FROM donotinvite
WHERE name = 'joe')
INSERT
INTO invites (name, message)
SELECT a.name, a.message
FROM (SELECT @name AS name, @message AS message) a
LEFT JOIN donotinvite d
ON a.name = d.name
WHERE d.name IS NULL
(I'm an MSSQL person, so not sure if all appropriate for MySQL) (我是MSSQL人员,所以不确定是否所有适合MySQL)
INSERT INTO invites
(
name, message
)
SELECT name = 'joe', message = 'This is an invite'
WHERE NOT EXISTS
(SELECT *
FROM donotinvite
WHERE name = 'joe')
In practice you might put all the Name / Message in a temporary table and then do: 在实践中,您可以将所有名称/消息放在临时表中,然后执行:
INSERT INTO invites
(
name, message
)
SELECT T.name, T.message
FROM MyTempTable AS T
WHERE NOT EXISTS
(
SELECT *
FROM donotinvite AS DNI
WHERE DNI.name = T.name
)
INSERT INTO invites (name, message)
SELECT 'joe', 'This is an invite' FROM (SELECT 1) t
WHERE NOT EXISTS (SELECT * FROM donotinvite WHERE name = 'joe');
This would do the job, but I'm not sure it would peform that well. 这样做可以完成这项工作,但我不确定它是否能很好地实现。 It might work for your application:
它可能适用于您的应用程序:
INSERT INTO invites(name, message)
SELECT p.name, "This is an invite"
FROM people AS p
WHERE p.name NOT IN (SELECT name FROM donotinvite);
Do you have a table like people
, a catalog of all the people you can send invites to? 你有一个像桌子
people
,都可以发送邀请给人们的一个目录?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.