好的,这是我第一次尝试CREATE FUNCTION
,所以请多多包涵!
所以,我有这个(简化的)表结构:
CREATE TABLE `pokemon` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`userid` INT UNSIGNED NOT NULL,
`boxid` TINYINT UNSIGNED NOT NULL DEFAULT 255,
`boxpos` SMALLINT UNSIGNED,
PRIMARY KEY (`id`),
UNIQUE KEY `position` (`userid`,`boxid`,`boxpos`)
) ENGINE=InnoDB
我想创建一个函数,给定用户 ID 和框 ID,返回一个空框位置(即不会触发重复键错误的位置)。
请注意,boxid
使用从 0 到 249 的值作为框 ID,并使用 255 作为用户方的特殊值。boxpos
Boxes 中的范围为 0 到 45,504,但 Party 中只有 0 到 5。此外,在 Party 中返回的位置应该是第一个空位置,而在 Box 中它应该是随机位置。
因此,考虑到所有这些,这是我的尝试:
begin
declare ret smallint unsigned;
declare exist tinyint unsigned default 1;
if fieldid = 255 then
create temporary table `party` (
`pos` smallint unsigned not null
);
insert into `party` values (0),(1),(2),(3),(4),(5);
delete from `party` where `pos` in (select `fieldpos` from `pokemon` where `userid`=userid and `fieldid`=255);
select `pos` into ret from `party` limit 1;
if ret is null then select `[[Error: No room in Party]]` from `party`; end if;
else
while exist=1 do
set exist=0;
set ret=floor(rand()*45504);
select 1 into exist from `pokemon` where `fieldid`=fieldid and `userid`=userid and `fieldpos`=ret;
end while;
end if;
return ret;
end;
(注意这是函数的主体,在 phpMyAdmin 中输入)
编辑:我已经解决了这个DECLARE
问题,但现在它说我不能从函数返回结果集。
我不确定我哪里出错了,我想我需要帮助才能走上正轨。特别是,我是否首先得到了正确的功能逻辑?