我使用'MariaDB 5.5 x64' and Client HeidiSQL
服务器环境是Windows Server2012 Datacenter
并且数据库use_progress
正在跟随
int id //自动增量主键
int owner //所有者用户的唯一ID
varchar [20] name // key
int值//值
它存储在线游戏用户的状态键值类型
例如
id owner name value
856 656 stage0cleared 0
857 656 have_gold 10214
858 657 inventory 22
并且下一个查询的工作测试很好
select count(*) from use_progress where owner = 656 and name = "inventory";
INSERT INTO use_progress (use_progress.owner, use_progress.name, use_progress.value) VALUES (656, 'inventory', 7);
UPDATE use_progress SET use_progress.value = 7 WHERE use_progress.`owner` = 656 AND use_progress.`name` = 'inventory';
但下一个查询是错误1064(语法错误)
BEGIN
IF ((select count(*) from use_progress where owner = 656 and name = "inventory") = 0 ) THEN
INSERT INTO use_progress (use_progress.owner, use_progress.name, use_progress.value) VALUES (656, 'inventory', 7);
ELSE
UPDATE use_progress SET use_progress.value = 7 WHERE use_progress.`owner` = 656 AND use_progress.`name` = 'inventory';
END IF;
END
错误正在接下来(总是那个错误):
/* SQL error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'IF ((select count(*) from use_progress where owner = 656 and name = "inventory")' at line 2 */
我尽我所能。是否使用()或不使用 dbname.tablename。前缀到每个列名称。但在任何情况下,都会发生同样的错误。
我甚至试过这个(第2行改变了):
BEGIN
IF (1>2) THEN
INSERT INTO use_progress (use_progress.owner, use_progress.name, use_progress.value) VALUES (656, 'inventory', 7);
ELSE
UPDATE use_progress SET use_progress.value = 7 WHERE use_progress.`owner` = 656 AND use_progress.`name` = 'inventory';
END IF;
END
但同样的错误发生(消息相同)
我不知道为什么会这样。
答案 0 :(得分:1)
您不能在简单查询中使用IF() THEN ...
等控制结构,只能在存储过程或函数中使用。
在这种情况下,您使用存储过程。试试这样:
DELIMITER $$
CREATE PROCEDURE my_proc_name(IN p_owner int, IN p_name varchar(50), IN p_value int)
BEGIN
IF NOT EXISTS (select 1 from use_progress where owner = p_owner and name = p_name) THEN
INSERT INTO use_progress (owner, name, `value`) VALUES (p_owner, p_name, p_value);
ELSE
UPDATE use_progress SET `value` = p_value WHERE `owner` = p_owner AND `name` = p_name;
END IF;
END $$
DELIMITER ;
创建后,您可以这样称呼它:
CALL my_proc_name(656, 'inventory', 7);