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.
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:
NOTE: a unique key may also span multiple rows. stupid example: combination of "ip" and "port" may be combined as the unique identifier "connection".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With