Created
October 15, 2014 17:23
-
-
Save mattvryan/4aab858722f0910e737f to your computer and use it in GitHub Desktop.
MySQL "INSERT ... WHERE NOT EXISTS" if you don't have/know a primary/unique key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INSERT INTO my_table (unique_but_non_indexed_col1, col2, col3) | |
SELECT * FROM (SELECT 'unique_val1', 'val2', 'val3') AS tmp | |
WHERE NOT EXISTS ( | |
SELECT id FROM my_table WHERE unique_but_non_indexed_col1='unique_val1' | |
) LIMIT 1; |
Probably not very performant, but useful for run-rarely scripts
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"my_table", "unique_but_non_indexed_col1", "col2", and "col3" are placeholders for the table and the columns needed, respectively.
"tmp" is not a placeholder per se but the name of a temporary table (could be anything).
"id" is the name of the primary key field in "my_table" ("id" is the convention) - it is not a placeholder.