简体   繁体   English

MySQL插入记录,如果不存在

[英]Mysql Insert record if not Exists

I have the following query 我有以下查询

INSERT INTO `title_servicemetadatafielddefinition` (`service_id`, `field`, `behavior`, `alt_label`, `localizable`, `custom_type`, `required`, `max_length`, `help_text`) 
VALUES (319, 'custom10', 'overridable', 'Rental Period', False, 'short_text', False, NULL, '24 hour;48 hour;72 hour;1 week;30 day;3 month;6 month;1 year') 
WHERE NOT EXISTS ( SELECT * FROM `title_servicemetadatafielddefinition` WHERE `service_id` = 319 and `field` = 'custom10' ) LIMIT 1;

Error 错误

You have an error in your SQL syntax; 您的SQL语法有误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS ( SELECT * FROM title_servicemetadatafielddefinition WHERE `s' at line 1 检查与您的MySQL服务器版本相对应的手册,以找到在'WHERE NOT EXISTS(SELECT * FROM title_servicemetadatafielddefinition WHERE`s')第1行附近使用的正确语法

and was failing when trying to execute, can't able to figure out what syntax was wrong 并且在尝试执行时失败,无法找出错误的语法

Below query will insert if row does not exist and ignore if already exist but make sure that service_id here should be either primary key or unique key. 如果行不存在,将在下面的查询中插入,如果行已存在,则将其忽略,但请确保此处的service_id应该是主键或唯一键。

INSERT IGNORE INTO `title_servicemetadatafielddefinition` (`service_id`, `field`, `behavior`, `alt_label`, `localizable`, `custom_type`, `required`, `max_length`, `help_text`) 
VALUES (319, 'custom10', 'overridable', 'Rental Period', False, 'short_text', False, NULL, '24 hour;48 hour;72 hour;1 week;30 day;3 month;6 month;1 year') 

Try this: 尝试这个:

INSERT INTO `title_servicemetadatafielddefinition` (`service_id`, `field`, `behavior`, `alt_label`, `localizable`, `custom_type`, `required`, `max_length`, `help_text`) 
SELECT 319, 'custom10', 'overridable', 'Rental Period', False, 'short_text', False, NULL, '24 hour;48 hour;72 hour;1 week;30 day;3 month;6 month;1 year'
FROM (SELECT 1) x
LEFT JOIN `title_servicemetadatafielddefinition` t
  ON t.`service_id` = 319 and t.`field` = 'custom10'
WHERE t.service_id IS NULL

You Wrote 'Limit' in INSERT STATEMENT. 您在INSERT STATEMENT中写了'Limit'。 I think, Limit should come in SELECT Statement. 我认为,限制应该出现在SELECT语句中。

INSERT INTO `title_servicemetadatafielddefinition` (`service_id`, `field`, `behavior`, `alt_label`, `localizable`, `custom_type`, `required`, `max_length`, `help_text`) 
VALUES (319, 'custom10', 'overridable', 'Rental Period', False, 'short_text', False, NULL, '24 hour;48 hour;72 hour;1 week;30 day;3 month;6 month;1 year') 
WHERE NOT EXISTS ( SELECT * FROM `title_servicemetadatafielddefinition` WHERE `service_id` = 319 and `field` = 'custom10' LIMIT 1); 

Use "LIMIT" in a MySQL "INSERT"? 在MySQL的“ INSERT”中使用“ LIMIT”?

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

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