Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL创建函数DFifulties_Mysql - Fatal编程技术网

MySQL创建函数DFifulties

MySQL创建函数DFifulties,mysql,Mysql,好的,这是我第一次尝试创建函数,请耐心等待 因此,我有这个(简化的)表结构: 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

好的,这是我第一次尝试
创建函数
,请耐心等待

因此,我有这个(简化的)表结构:

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之间的值作为box id,255作为用户方的特殊值
boxpos
在盒子中的范围为0到45504,但在参与方中仅为0到5。此外,在参与方中,返回的位置应为第一个空位置,而在框中,返回的位置应为随机位置

因此,考虑到所有这些,我的尝试如下:

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
问题,但是现在它说我不能从函数返回结果集

我不确定哪里出了问题,我想我需要帮助才能走上正轨。特别是,我是否首先正确地理解了功能逻辑?

在这一行:

if ret is null then select `[[Error: No room in Party]]` from `party`; end if;
您可以从
party
表中为所有行选择一个常量值,但不将该选择的结果放入变量中。这可能就是错误的来源

可能应该是这样的:

if ret is null then 
   set ret = '[[Error: No room in Party]]';
end if;

(还请注意,字符串文字需要用单引号(
)括起来,而不是用那些可怕的反勾号——它们在一开始是不必要的,所以最好将它们全部省略掉。)

这一行的要点是抛出一个错误,因为我使用的是5.5之前的MySQL版本。如果团队中没有空间,我需要该函数来中断正在运行的查询。@Kolink:MySQL不支持抛出异常吗?@Kolink:这很蹩脚(但我并不感到惊讶…)。也许您可以执行无效的动态SQL(使用
PREPARE
),以便在创建过程时不检查SQL。我可以通过将
添加到exist
中来修复它。这样,查询结果就会被放入一个变量中。