Reputation: 2461
I want to insert values into a table but need to check if the value exist in the last row or not. I normally insert values like
INSERT INTO `table` (`column1`,`column2`,`column3`,`column4`) VALUES ('value1','value2','value3','value4')
But now I need to put a check, if the value1 exist in the last row of the table do not insert, insert otherwise.
For that I am trying to use
WHERE NOT EXISTS
I actually want to check the last row of the table if the value exist then it should not duplicate it.
Upvotes: 0
Views: 1268
Reputation: 5666
You can state explicitly what happens when the primary key for a table already exists. Example:
INSERT INTO table (...) VALUES (...) ON DUPLICATE KEY UPDATE
Upvotes: 1
Reputation: 1393
Adding an unique constraint on the pair (column 1, column 2) isn't a better way to do that ?
Upvotes: 0
Reputation: 28379
as an aside, as per the documentation, in the WHERE NOT EXISTS select, you don't need to specify fields (value1, value2, in your case) because that is entirely ignored. So just use *
In any event, I believe this will answer your question: How to 'insert if not exists' in MySQL?
Upvotes: 0