INSERT WHERE NOT EXISTS

Apr 18 2012 12:00 PM APR 18 2012 12:00 PM
MySQL INSERT IF ROW DOES NOT EXISTMySQL

Recently I needed to create a patch for a project and we have references in our database for wizards. These wizards exist in each folder, but cannot have more than one at a time in each folder. Currently the table does not have a unique key so I could not use:

INSERT IGNORE

 

Because of this I resorted to the following:

INSERT INTO tblName (reportName, folderId) 
SELECT 'Wizard', 1 FROM tblName2 WHERE NOT EXISTS 
(SELECT 1 FROM tblName2 WHERE reportName='Wizard' AND folderId = 1) LIMIT 1;

Hope it helps someone...