Skip to content

Instantly share code, notes, and snippets.

@mttjohnson
Created December 14, 2018 21:23
Show Gist options
  • Select an option

  • Save mttjohnson/1041f51224589ecda8935d41e7cf0884 to your computer and use it in GitHub Desktop.

Select an option

Save mttjohnson/1041f51224589ecda8935d41e7cf0884 to your computer and use it in GitHub Desktop.
MySQL Insert/Update or both
-- In the below example there is a unique key for scope, scope_id, and path
-- We can choose to only insert a record if it doesn't exist, only update
-- a record that doesn't exist, or accomodate both to ensure that a record
-- exists afterwards, either inserted, or updated for the matching key.
-- Only insert a record if it does not already exist
INSERT INTO core_config_data (scope, scope_id, path, value)
SELECT * FROM (SELECT 'default', '0', 'catalog/search/engine', 'enterprise_search/engine') AS to_insert
WHERE NOT EXISTS (
SELECT path FROM core_config_data WHERE scope = 'default' and scope_id = 'default' and path = 'catalog/search/engine'
) LIMIT 1;
-- or
INSERT IGNORE INTO core_config_data
(scope, scope_id, path, value)
VALUES
('default', '0', 'catalog/search/engine', 'enterprise_search/engine');
-- Only update an existing record otherwise do nothing
UPDATE core_config_data SET value = 'enterprise_search/engine' WHERE path = 'catalog/search/engine';
-- Either Insert new record or update existing record if duplicate key exists
-- This works for duplicate unique or primary keys
-- This seems similar to a term I've heard of called "indate" where an insert is
-- tried first, and if that can not complete an update is performed. That being
-- a bit different than "upsert" an attempt to update, and if failed, insert, which
-- seems similar but may not be the same. I don't believe there is anything in
-- MySQL directly referencing upsert/indate support, but this affectively accomodate
-- the same kind of need provided it can be triggered around a unique key.
INSERT INTO core_config_data (scope, scope_id, path, value)
VALUES ('default', '0', 'catalog/search/engine', 'enterprise_search/engine')
ON DUPLICATE KEY UPDATE
value = '1';
-- or
SET @scope = 'default',
@scope_id = '0',
@path = 'catalog/search/engine',
@value = 'enterprise_search/engine';
INSERT INTO core_config_data
(scope, scope_id, path, value)
VALUES
(@scope, @scope_id, @path, @value)
ON DUPLICATE KEY UPDATE
value = @value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment