Insert where not exists
Posted: March 21st, 2008 | Author: Tim | Filed under: Uncategorized | Tags: mysql | 7 Comments »If you want to insert values into a MySQL table, but only if those values don’t already exist, and you don’t want to use a primary key on the table (and deal with the resulting error suppression ), here’s an elegant one-query method of doing so.
INSERT INTO [table name] SELECT '[value1]', '[value2]' FROM DUAL
WHERE NOT EXISTS(
SELECT [column1] FROM [same table name]
WHERE [column1]='[value1]'
AND [column2]='[value2]' LIMIT 1
)
OK, technically it’s not a single query. But it is only one round trip to the MySQL server.
Hat tip to Matt Mongeau
[...] Insert where not exists by Tim Share and Enjoy: These icons link to social bookmarking sites where readers can share and [...]
Not exactly looking for this query but, it’s always cool to see another Orlando person writing the code. Good all the same, Cheers.
Good to know you too! There’s quite a few of us. You should come out to the local events: Florida Creatives, ORUG, Likemind, and all the rest. Check out Ryan’s event calendar: http://upcoming.yahoo.com/group/2967/
(Tip: I’m actually not going to be an Orlando-ian for much longer…moving to San Francisco at the end of April)
This worked like a charm!, i tried using INSERT IGNORE INTO, but that wont work unless the whole row is an exact duplicate of a previous row! FROM DUAL WHERE NOT EXISTS rocks
Together……
[...]Without having any risk of getting impacted by recession[...]…
Gems form the internet…
[...]very few websites that happen to be detailed below, from our point of view are undoubtedly well worth checking out[...]……
Crazy Ideas…
…Why do so many visitors disagree……