I was building a queue of projects with statuses into a mysql table. In my situation, I was expecting to have a project number, and a status. There’s a possibility that there would be many non-unique entries, wherein the same project was published over and over successfully. I wanted to add a new line to the table only if there wasn’t already an existing request for the current project to be built. Most of the examples out there assume you can use unique identifiers, or use two calls to solve this, but I wanted a single mysql call to solve the whole thing.
I found some good stuff on this, but only one answer actually gave me what I was looking for:
If you have a situation where you can’t use unique data:
NOTE: Your database table must not be empty for this to work.
INSERT INTO `table` (`value1`, `value2`) SELECT 'stuff for value1', 'stuff for value2' FROM `table` WHERE NOT EXISTS (SELECT * FROM `table` WHERE `value1`='stuff for value1' AND `value2`='stuff for value2') LIMIT 1
If you CAN use unique identifiers on your table, then this should work for you.
INSERT IGNORE INTO `table` SET `value1` = 'stuff for value1', `value2` = 'stuff for value2';
thanks to: this page