Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert or update (if exists) without primary key

Tags:

php

mysql

I have the following database MySQL table.

  • id (PK, AI)
  • email
  • country
  • lastlogin

I have a regular query in PHP that inserts this into the table. however, logically, if this code runs several times, the same row will be inserted to the database every time.

I want my reference for checking and duplication to be the email field, and if the email is the same, update the country and the lastlogin.

I checked on other questions for a similar issue and the suggested way was to use ON DUPLICATE KEY like this

INSERT INTO <table> (field1, field2, field3, ...) 
VALUES ('value1', 'value2','value3', ...)
ON DUPLICATE KEY UPDATE
field1='value1', field2='value2', field3='value3', ...

However, my primary key is not the email field rather the id but I don't want to run the check on it.

like image 234
tony9099 Avatar asked Mar 10 '17 07:03

tony9099


People also ask

Can we update a table without primary key?

However, UPDATE works without a PK. If there are dups, they will be updating to the same value. A primary key is a special case of an index -- specifically, a primary key is a unique identifier for an individual row in a table.

Can we use insert instead of update?

No. Insert will only create a new row.

Does MySQL update insert if not exists?

MySQL doesn't have a statement to insert a new row if the data do not exist. This is because when you have table column(s) with PRIMARY KEY or UNIQUE constraint, then MySQL will throw an error each time your query inserts a new row with duplicate values for those columns.

What is the difference between insert and update?

Insert is for adding data to the table, update is for updating data that is already in the table.


1 Answers

One option is make the email field unique, and then it should behave the same as primary key, at least with regard to MySQL's ON DUPLICATE KEY UPDATE:

ALTER TABLE yourTable ADD UNIQUE INDEX `idx_email` (`email`);

and then:

INSERT INTO yourTable (email, country, lastlogin)
VALUES ('[email protected]', 'value2', 'value3')
ON DUPLICATE KEY UPDATE
    email='value1', country='value2', lastlogin='value3'

If the email [email protected] already exists in your table, then the update would kick in with alternative values.

From the MySQL documentation:

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, MySQL performs an UPDATE of the old row.

This approach doesn't only work with primary keys, it also works with any column having a unique index.

like image 97
Tim Biegeleisen Avatar answered Sep 28 '22 19:09

Tim Biegeleisen