Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ON DUPLICATE KEY UPDATE in MySQL without a UNIQUE index or PRIMARY KEY?

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?

like image 299
B Seven Avatar asked Jun 22 '12 15:06

B Seven


People also ask

What is the use of on duplicate key update 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.

Can you have duplicate primary keys MySQL?

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.

How do I duplicate a key in MySQL?

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.

How do I allow duplicates in a primary key?

You can't have duplicate values in the primary key or else it wouldn't be a primary key.


2 Answers

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?

like image 90
Kermit Avatar answered Sep 28 '22 03:09

Kermit


Try this:

INSERT INTO `table` (userid)
SELECT 'value for userid' FROM `table` 
  WHERE userid = 'value for userid' HAVING count(*) = 0
like image 44
Jeetendra Pujari Avatar answered Sep 28 '22 03:09

Jeetendra Pujari