MySQL如果存在,则返回' id'字段else插入新行并返回最后插入的id?

时间:2013-04-24 10:25:50

标签: mysql

这句话有什么问题?

IF EXISTS (
SELECT * 
FROM `apples` 
WHERE `apples`.`color` = ? 
AND `apples`.`size` = ?) 
SELECT `apples`.`applesID` 
ELSE 
INSERT INTO `apples` (`color`, `size`) 
VALUES(?,?);

1 个答案:

答案 0 :(得分:0)

您没有使用IF的正确语法:

IF EXISTS (
    SELECT * 
    FROM `apples` 
    WHERE `apples`.`color` = ? 
    AND `apples`.`size` = ?) THEN
    SELECT `apples`.`applesID`;
ELSE 
    INSERT INTO `apples` (`color`, `size`) VALUES(?,?);
END IF;