Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL INSERT IF NOT EXIST else DELETE row

Tags:

mysql

I have a table that links 2 other tables together.

I have a list of checkboxes, where when one is checked, it sends the value to the server via ajax.

What I want to do is if the values are not in the database, insert them (checked) or if they are there, delete them (unchecked)

Is there a way to do it without writing several queries? I know its not to hard with an insert/update, but what about delete?

like image 941
guyfromfl Avatar asked Nov 09 '11 21:11

guyfromfl


People also ask

How do you insert if row does not exist in MySQL?

There are three ways you can perform an “insert if not exists” query in MySQL: Using the INSERT IGNORE statement. Using the ON DUPLICATE KEY UPDATE clause. Or using the REPLACE statement.

Does MySQL update insert if not exists?

Often you have the situation that you need to check if an table entry exists, before you can make an update. If it does not exist, you have to do an insert first. Unfortunately, this the 'ON DUPLICATE KEY' statement only works on PRIMARY KEY and UNIQUE columns.


1 Answers

You can allways delete and, if affected rows is 0, then insert. Easy, simple and it works.

like image 62
dani herrera Avatar answered Oct 13 '22 01:10

dani herrera