[英]Checking for data before inserting into MySQL DB
I am creating an SQL script that will add specific entries to the DB when run on a new environment. 我正在创建一个SQL脚本,当在新环境中运行时,该脚本将向DB添加特定条目。 But I want to have to INSERT query insure that the data doesn't already exist before trying to insert it.
但是我想必须进行INSERT查询,以确保在尝试插入数据之前数据不存在。
The query I came up with looks sound to me. 我提出的查询对我来说听起来很合理。 But for some reason it gives me a syntax error.
但是由于某种原因,它给了我一个语法错误。 And yes I have RTFM'ed it.
是的,我已经过RTFM。 And I have Googled it.
而且我已经用谷歌搜索了。 Based on other examples that I have seen (even here on Stack Exchange) it looks right to me.
根据我所看到的其他示例(即使在Stack Exchange上也是如此),它对我来说似乎很正确。 Can anyone identify what I am doing wrong?
谁能识别我在做什么错?
Query: 查询:
INSERT INTO my_model (status, name) VALUES ('active', 'bbc')
WHERE NOT EXISTS (SELECT name FROM my_model WHERE name = 'bbc')
Any ideas? 有任何想法吗?
The plain INSERT
doesn't allow a WHERE
. 普通
INSERT
不允许WHERE
。 If the primary key is (status, name)
then use INSERT IGNORE
as @aynber exists. 如果主键是
(status, name)
则使用INSERT IGNORE
,因为存在@aynber。 If not, try INSERT ... SELECT
: 如果没有,请尝试
INSERT ... SELECT
:
INSERT INTO my_model (status, name)
SELECT 'active', 'bbc'
FROM DUAL
WHERE NOT EXISTS (SELECT name FROM my_model WHERE name = 'bbc');
DUAL
is a system-supplied one-row table, used to guarantee one row of results for something like SELECT 'active', 'bbc' FROM DUAL
. DUAL
是系统提供的单行表,用于保证SELECT 'active', 'bbc' FROM DUAL
类的结果的一行。 It's an Oracle "invention" but supported in MySQL. 这是Oracle的“发明”,但在MySQL中受支持。 You may be able to drop the
FROM DUAL
from the query; 您也许可以从查询中删除
FROM DUAL
; I don't have MySQL today so I can't test it to be sure. 我今天没有MySQL,因此无法确定是否进行测试。
try this: 尝试这个:
INSERT INTO my_model (status, name) select('active', 'bbc') from my_model
WHERE NOT EXISTS (SELECT name FROM my_model WHERE name = 'bbc');
You want INSERT IGNORE
instead of NOT EXISTS
, if name
is a primary/unique key. 如果
name
是主键/唯一键,则需要INSERT IGNORE
而不是NOT EXISTS
。 This will not insert anything if it hits a duplicate key error. 如果遇到重复的键错误,则不会插入任何内容。 You can also use
ON DUPLICATE KEY UPDATE
if you want to update a column if the row already exists. 如果要更新已存在的列,也可以使用
ON DUPLICATE KEY UPDATE
。
in sql i would create a stored procedure not sure if you can in mysql 在SQL中,我会创建一个存储过程,不确定是否可以在MySQL中
if !(SELECT name FROM my_model WHERE name = 'bbc') BEGIN INSERT INTO my_model (status, name) VALUES ('active', 'bbc') END 如果!(从my_model的名称中选择名称='bbc')开始插入my_model(状态,名称)值('active','bbc')END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.