Skip to content
Advertisement

Is it possible to update or insert if not exist in MySQL using where-in clause without primary key?

Below is my database table.

Below is my data:

I want the following result in my database table.

How to write MySQL query without executing select query first? In my case there is no primary key.

Advertisement

Answer

You can use MySQL insert ... on duplicate key update ... syntax:

For this to work, you need to set up a unique key constraint on columns (role, type). Create it if it doesn’t yet exist:

This syntax can also be used to process multiple inserts at a time:

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