6

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

0

2 Answers 2

5

You need to add a UNIQUE KEY on those columns:

ALTER TABLE FAV_TABLE ADD UNIQUE KEY(uid, fav_id);
Sign up to request clarification or add additional context in comments.

Comments

2

INSERT IGNORE or ON DUPLICATE KEY works only when a unique key is duplicated.

You need to add a UNIQUE index on both fields uid and fav_id. That way, when you insert a duplicate pair, it will be ignored.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.