I have multiple columns in a table. I have a unique column, if the entry is duplicate to this column I would like the two columns be updated otherwise insert new row. I am using a separate function in php, but for simplicity I will share the mysql code. In this case col1 is fixed. Insert row if col1 is not duplicate. But this simply inserts a new row even if col1 is duplicate. Also col4 can be null. All the SO questions didn't address my issue.
INSERT INTO table1
(col1, col2, col3, col4)
VALUES
('val1', 'val2', 'val3', 'val4')
ON DUPLICATE KEY UPDATE
col2=VALUES(col2)
col3=VALUES(col3)
It doesn't work cause you don't have a UNIQUE
key defined on col1
column. Per INSERT ... ON DUPLICATE KEY UPDATE Documentation
if insertion causes duplicate key violation in UNIQUE/PrimaryKey
column then UPDATE
takes place instead if INSERT
.
So in your case you will have to make col1
a key column either by defining a primary key / unique key constraint on the column; in order to have it worked.