Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - INSERT ON DUPLICATE KEY - 2 columns

Tags:

mysql

I am going to be logging the IP addresses that my users log in with. To do this, I have a simple table with 3 columns: user, ip, time. time is the time at which they last logged in with that address.

When they log in, I want to insert a row into the database containing the IP they logged in with, and the time they logged in.

If a row with the same user AND same ip already exists, I just want to update the time. A more general question:

How can I INSERT a row, or UPDATE it if two (or more) of its columns are the same?

like image 796
Jacob Brunson Avatar asked Jun 12 '12 22:06

Jacob Brunson


People also ask

How do I find duplicate values in two columns in MySQL?

Find Duplicate Row values in Multiple ColumnsSELECT col1, col2,..., COUNT(*) FROM table_name GROUP BY col1, col2, ... HAVING (COUNT(col1) > 1) AND (COUNT(col2) > 1) AND ... In the above query, we do a GROUP BY of all the columns (col1, col2) for whom we want to find duplicates.

Is insert on duplicate key update Atomic?

By definition, atomicity requires that each transaction is an all or nothing. So yes it is atomic in the sense that if the data that you are trying to insert will cause a duplicate in the primary key or in the unique index, the statement will instead perform an update and not error out.

How do you insert duplicate values?

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.

What is the syntax to insert a record value1 value2 into a table with two fields?

There are two basic syntax of INSERT INTO statement is as follows: INSERT INTO TABLE_NAME (column1, column2, column3,... columnN)] VALUES (value1, value2, value3,... valueN);


1 Answers

You just need to create composite unique key user + ip and use INSERT ON DUPLICATE KEY UPDATE

INSERT INTO tbl (user, ip, `time`) VALUES (1, '1.2.3.4', NOW())
ON DUPLICATE KEY UPDATE `time` = NOW()

To create index use something like

CREATE UNIQUE INDEX tbl_user_ip ON tbl (user, ip)
like image 52
zerkms Avatar answered Sep 25 '22 10:09

zerkms