The MySQL manual states:
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY
What if you have a table that does not have a UNIQUE index or PRIMARY KEY, but you don't want to duplicate an entry for a column (say user_id).
Is there a way to do it in MySQL?
ON DUPLICATE KEY UPDATE inserts or updates a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas. The use of VALUES() to refer to the new row and columns is deprecated beginning with MySQL 8.0.
You can define keys which allow duplicate values. However, do not allow duplicates on primary keys as the value of a record's primary key must be unique.
The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.
You can't have duplicate values in the primary key or else it wouldn't be a primary key.
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
Source: How to 'insert if not exists' in MySQL?
Try this:
INSERT INTO `table` (userid)
SELECT 'value for userid' FROM `table`
WHERE userid = 'value for userid' HAVING count(*) = 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With