Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Create an UNIQUE index on two columns for ON DUPLICATE KEY

Tags:

sql

mysql

I have a table with 4 columns. I want to be able to INSERT or UPDATE the value column on creation (I don't care about indexes row ID's).

CREAT TABLE tablename (
 id,   (primary)
 user_id, (index)
 setting_id, (index)
 value  (index)
);

Originally I was going to run a "REPLACE INTO..." query each time I wanted to save a value. But then I read about the problems and instead chose a INSERT INTO... ON DUPLICATE KEY UPDATE.

The problem is that I don't have single column for the "INSERT INTO... ON DUPLICATE KEY UPDATE" to use to figure out if this is a new row or if there is an existing row that needs to be updated.

So I figured that I would use a UNIQUE key that was a mix of the two columns that made this row unique (

CREATE UNIQUE INDEX index_name ON table(user_id, setting_id);

However, I'm not sure how to advance from here. How do I structure my queries to check this new INDEX when trying to figure out a row already exists with these two column values?

INSERT INTO `tablename` (value, user_id, setting_id) VALUES (1,34,15) ON DUPLICATE KEY UPDATE

:EDIT:

By removing the ID primary column leaving only (setting_id, user_id, & value) I was able to create a PRIMARY index on (setting_id, user_id) and then the following query worked. more help here.

INSERT INTO tablename (user_id, setting_id, value)
VALUES (42, 1, 12)
ON DUPLICATE KEY UPDATE value = 12
like image 341
Xeoncross Avatar asked Oct 19 '09 23:10

Xeoncross


People also ask

Can unique index have duplicate values?

No, you cannot create a Unique Index on a table that has duplicate values.

How do I make two columns unique in MySQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in MySQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.

Can unique key have multiple columns?

A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table. You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate values.

How do I create a composite unique index in MySQL?

Creating Composite IndexCREATE TABLE table_name ( c1 data_type PRIMARY KEY, c2 data_type, c3 data_type, c4 data_type, INDEX index_name (c2,c3,c4) ); In the above statement, the composite index consists of three columns c2, c3, and c4.


1 Answers

The query you have would end up looking something like this...

INSERT INTO table (value,user_id,setting_id) VALUES (1,34,15)
  ON DUPLICATE KEY UPDATE value = 1, user_id = 34, setting_id = 15;
like image 170
Chris Gutierrez Avatar answered Nov 14 '22 22:11

Chris Gutierrez