IF EXISTS语句给出错误#1064

时间:2016-05-14 19:32:22

标签: mysql database if-statement exists

似乎无法获得一个简单的if exists语句在mysql中工作,是否有可能导致它无法正常工作?

IF EXISTS(SELECT * FROM Cookies WHERE VALUED ='2601:2c0:8403:5320:947e:a047:6e0f:e23a')
BEGIN
THEN
END;
    UPDATE Cookies SET Amount = Amount + '1' WHERE VALUED ='2601:2c0:8403:5320:947e:a047:6e0f:e23a'

ELSE 
BEGIN

    INSERT INTO Cookies (Valued, Amount) Values ('2601:2c0:8403:5320:947e:a047:6e0f:e23a', '1' )
END;

2 个答案:

答案 0 :(得分:2)

删除所有BEGIN和END - 您不需要它们并且您无论如何都使用了它们:

IF EXISTS(SELECT * FROM Cookies WHERE VALUED ='2601:2c0:8403:5320:947e:a047:6e0f:e23a') THEN
    UPDATE Cookies SET
    Amount = Amount + '1'
    WHERE VALUED ='2601:2c0:8403:5320:947e:a047:6e0f:e23a'
ELSE 
    INSERT INTO Cookies (Valued, Amount) Values 
    ('2601:2c0:8403:5320:947e:a047:6e0f:e23a', '1' );
END IF;

如果VALUED是主键,则可以更简单地执行此操作:

insert into Cookies (Valued, Amount) values 
('2601:2c0:8403:5320:947e:a047:6e0f:e23a', 1 )
on duplicate key update Amount = Amount + 1;

答案 1 :(得分:0)

您似乎搞砸了thenbegin关键字的顺序:

IF EXISTS(SELECT * FROM Cookies WHERE VALUED ='2601:2c0:8403:5320:947e:a047:6e0f:e23a')
THEN -- Here!
BEGIN
    UPDATE Cookies SET Amount = Amount + '1' WHERE VALUED ='2601:2c0:8403:5320:947e:a047:6e0f:e23a'
END;    
ELSE 
BEGIN
    INSERT INTO Cookies (Valued, Amount) Values ('2601:2c0:8403:5320:947e:a047:6e0f:e23a', '1' )
END;

编辑:
假设valued是主键(或者甚至只是唯一键),使用带有on duplicate子句的insert语句会更容易:

INSERT INTO cookies (valued, amount)
VALUES ('2601:2c0:8403:5320:947e:a047:6e0f:e23a', 1)
ON DUPLICATE KEY UPDATE amount = amount + 1;