[英]Mysql Insert record if not Exists
我有以下查询
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`s')第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')
尝试这个:
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
您在INSERT STATEMENT中写了'Limit'。 我认为,限制应该出现在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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.