简体   繁体   中英

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; 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

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.

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. I think, Limit should come in SELECT Statement.

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"?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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