Mysql如果不存在则插入记录

时间:2015-09-01 09:55:32

标签: mysql insert-into

我有以下查询

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;

错误

  

您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以便在'WHERE NOT EXISTS附近使用正确的语法(SELECT * FROM title_servicemetadatafielddefinition WHERE`在第1行

并且在尝试执行时失败,无法弄清楚哪种语法错误

3 个答案:

答案 0 :(得分:1)

如果行不存在,则下面的查询将插入,如果已存在则忽略,但请确保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') 

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

你在INSERT 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"?