Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL INSERT IGNORE or ON DUPLICATE KEY DO_NOTHING

Tags:

mysql

already searched for such topics and found 2 different solutions but noone works.

My table has structure | ID (auto_increment primary_key) | UID (int) | FAV_ID (int) |

I need to insert new record to this FAV_TABLE if UID and FAV_ID (both) already exist.

Example of my query:

INSERT INTO FAV_TABLE (uid, fav_id) VALUES ($u_id,$s_id) ON DUPLICATE KEY UPDATE  uid = uid 

or this one

INSERT IGNORE FAV_TABLE (uid, fav_id) VALUES ($u_id,$s_id);

As mysql manuals says this query doesn't add record only if PRIMARY_KEY is the same. And I need query not to add record if pair uid+fav_id is unique. Any solutions? Thank you

like image 763
265 Avatar asked Apr 28 '12 16:04

265


1 Answers

You need to add a UNIQUE KEY on those columns:

ALTER TABLE FAV_TABLE ADD UNIQUE KEY(uid, fav_id);
like image 81
eggyal Avatar answered Nov 25 '22 07:11

eggyal