Skip to content
Advertisement

How do I update if exist, else insert in MySQL

I have table with AUTO_INCREMENT field defined as PRIMARY_KEY.

I have columns like: vote_id,vote_user_id,vote_ask_id,vote_comment_id,vote_post_id,vote_type,vote_status

I want to INSERT new records but before I do that I want to check if there is a row with columns(vote_user_id,vote_ask_id,vote_type) as same as the new data I want INSERT.

I have searched the internet and learnt about MySQL ..ON DUPLICATE KEY UPDATE. I have realize this statement will not be helpful to my task since it only checks for DUPLICATE KEY(…PRIMARY_KEY or UNIQUE FIELD). I have learnt also on MySQL REPLACE INTO …and likewise this will not be helpful to my problem since that is also bind to PRIMARY_KEY or UNIQUE index.

I learnt I could use MERGE….USING…statements but this was giving me errors so i read more about it and I relised it only work in SQL server (Microsoft)

Please how best can someone help me solve this?

I tried this on MERGE staments:

Advertisement

Answer

In MySQL, use ON DUPLICATE KEY:

For this to work, you need a unique index/constraint on the columns that define a unique row:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement