Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If (SELECT...) = 0 INSERT . in MySql

I am used to doing this in sql server

IF (SELECT COUNT(*) FROM table WHERE column1=@value1) = 0
INSERT INTO table(column1, column2, column3) VALUES(@value1, @value2, @value3)

But I can't really get it to work in MySql. Please help :)

---------------- EDIT ------------------

There shouldn't be a lot of fuss or magic involved in this, I would assume.

If an e-mail does not exist in a table then insert several values into that table.

That's it. Preferbly a one liner, to embed in programming code.

like image 917
Jesper Avatar asked Nov 19 '25 04:11

Jesper


1 Answers

another way to do this is using the INSERT IGNORE statement. Assuming column1 should only hold unique values, you can add a UNIQUE KEY constraint on the field (if its not your primary key already):

ALTER TABLE table ADD UNIQUE KEY column1 (column1)

you can then write your query as such:

INSERT IGNORE INTO table(column1, column2, column3) VALUES(@value1, @value2, @value3)

or if you want to automatically update the other fields, use ON DUPLICATE KEY UPDATE:

INSERT INTO table(column1, column2, column3) VALUES(@value1, @value2, @value3) 
ON DUPLICATE KEY UPDATE column2 = @value2,  column3 = @value3

letting the database handle it automatically using unique key has several advantages:

  • better performance and scalability through usage of indexes as opposed to full table scans
  • failsafe - you can not add two rows with same unique identifier accidentally with a wrong query
  • better readability of your queries

NOTE: a unique key may also span multiple rows. stupid example: combination of "ip" and "port" may be combined as the unique identifier "connection".

like image 163
Kaii Avatar answered Nov 21 '25 18:11

Kaii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!