我正在创建一个存储过程来将值插入到四个表中。关键是要从SQL中取出SQL以防止SQL注入并更好地定义用户拥有的权限,即不允许无限制地访问INSERT
,SELECT
,ALTER
和DELETE
语句,只允许它们运行插入传递的变量所需的过程。
然而,如果一个玩家已经存在,那么就没有必要再次添加它(考虑到我已经使它独一无二,这是不可能的)。出现问题是因为播放器表和坐标表之间存在一对多的关系。
所以我想要的是一个条件INSERT
来测试该值是否已经存在,以及是否继续执行下一个INSERT
语句。
这是存储过程:
CREATE PROCEDURE `acdb_extended`.`addAlliedMember` (IN accountNumber VARCHAR(255),
IN userName VARCHAR(255), IN serverInitial CHAR(1), IN galaxy TINYINT(2),
IN region TINYINT(2), IN system TINYINT(2), IN astro TINYINT(2), IN level TINYINT(2),
IN allianceName VARCHAR(255))
BEGIN
INSERT INTO player (account_number, username)
VALUES (accountNumber, userName);
INSERT INTO coordinates (player_ID, server_initial, galaxy, region, system, astro)
VALUES ((SELECT player_ID FROM player WHERE username = userName), serverInitial,
galaxy, region, system, astro);
INSERT INTO jumpgate (player_ID, coordinates_ID, level, usable)
VALUES ((SELECT player_ID FROM player WHERE username = userName),
(SELECT c.coordinates_ID FROM coordinates c WHERE c.server_initial = serverInitial
AND c.galaxy = galaxy AND c.region = region AND c.system = system AND c.astro = astro),
level, FALSE);
INSERT INTO relationship (player_ID, ally, alliance_name)
VALUES ((SELECT player_ID FROM player WHERE username = userName),
TRUE, allianceName);
END
我想我需要ON DUPLICATE KEY
,但我无法弄清楚它的用法。
提前感谢所有帮助。
答案 0 :(得分:1)
使用MySQL有几种方法可以做到这一点。一个简单的解决方案是使用INSERT IGNORE
而不是INSERT
。如果新行重复表中的现有UNIQUE INDEX
或PRIMARY KEY
值,则前者基本上不执行任何操作。有关详细信息,请参阅INSERT Syntax上的MySQL文档。
您还可以使用提供更多灵活性的语法INSERT INTO ... SELECT ...
。让我们举一个简单的例子。以下陈述基本上做同样的事情:
INSERT INTO foobar (foobar_id,display_name) VALUES (1,'one');
INSERT INTO foobar (foobar_id,display_name)
SELECT 1,'one' FROM dual;
如果您更改SELECT
查询以检测foobar中的重复条目,则会获得所需的行为。有关详细信息,请参阅INSERT ... SELECT Syntax上的MySQL文档。
编辑:这适用于存储过程以及存储过程的参数:
CREATE PROCEDURE sp_foobar(IN _foobar_id int, IN _display_name varchar(255))
BEGIN
INSERT INTO foobar (foobar_id, display_name)
SELECT _foobar_id, _display_name
FROM dual;
END;
答案 1 :(得分:0)
你不能这样做吗:
IF NOT EXISTS(SELECT NULL FROM player WHERE account_number=accountNumber AND username=userName)
BEGIN
INSERT INTO player (account_number, username)
VALUES (accountNumber, userName);
INSERT INTO coordinates (player_ID, server_initial, galaxy, region, system, astro)
VALUES ((SELECT player_ID FROM player WHERE username = userName), serverInitial,
galaxy, region, system, astro);
END