Reputation: 3720
I want to be able to do something like this:
IF EXISTS (SELECT * FROM table WHERE col=val)
INSERT ......
ELSE
UPDATE ......
I know that you are able to do this:
IF EXISTS (SELECT * FROM table WHERE col=val)
INSERT ......
But I'm not sure if you can do an else along with that.
What would fastest way to do the first query?
Upvotes: 0
Views: 29
Reputation: 77846
You should rather use INSERT ... ON DUPLICATE KEY UPDATE
insert into table1 (col1,col2) values(1,2)
on duplicate key update col2=3, col1=4
See Here for more information.
Upvotes: 0
Reputation: 7552
Yes it is possible. One way to do this is by using a procedure.
DELIMITER $$
DROP PROCEDURE IF EXISTS `YOUR-PROCEDURE`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `YOUR-PROCEDURE`()
BEGIN
IF EXISTS (SELECT * FROM table WHERE col=val)
THEN
BEGIN
UPDATE table SET ..;
END;
ELSE
BEGIN
INSERT INTO table ..;
END;
END IF;
END$$
DELIMITER ;
Upvotes: 1