gpt4 book ai didi

MYSQL 从函数返回行数

转载 作者:行者123 更新时间:2023-11-29 22:14:07 26 4
gpt4 key购买 nike

因此,我有一个包含游戏分数的表,将其命名为 RESULTS_TABLE,为了简单起见,我们假设它包含以下列:

year - tournament - GameID -  player1 - player2 - winner

相同的玩家可以在一场锦标赛中玩多场比赛,在这种情况下,您将拥有具有相同玩家 1/玩家 2 但不同 GameID 的多条线路。

我想写的是一个函数,它返回一个玩家在给定锦标赛中的对手数量

我使用 MYSQL 工作台。在命令窗口中我运行了以下命令:

select SQL_CALC_FOUND_ROWS year from RESULTS_TABLE where player1 = 'NAME' and comp = 'COMP' and year = 2015 group by player2;
select FOUND_ROWS()

这将返回玩家在表中列为玩家 1 时拥有的对手数量。如果我再次选择交换玩家 1 和玩家 2,我将获得该玩家列为玩家 2 时拥有的对手数量。添加这些将得到所需的结果。

我尝试使用一个函数来实现此目的,以 _comp、_year 和 _nick 作为输入参数:

BEGIN
declare NumOfOppos int;
declare oppos1 int;
declare oppos2 int;

select SQL_CALC_FOUND_ROWS year from RESULTS_TABLE where player1 = _nick and comp = _comp and year = _year group by player2;

select FOUND_ROWS() into oppos1;

select SQL_CALC_FOUND_ROWS year from RESULTS_TABLE where player2 = _nick and comp = _comp and year = _year group by player1;

select FOUND_ROWS() into oppos2;

select (oppos1+oppos2) into NumOfOppos;

return NumOfOppos;
END

但是,在尝试创建该函数时,会出现以下错误:

错误 1415:不允许从函数返回结果集

我不明白...我到底在哪里返回一组,我只想返回一个值,并且我相信我所做的...

非常感谢任何帮助。

最佳答案

在一个查询中完成这一切怎么样?

select count(*)
from RESULTS_TABLE
where comp = 'COMP' and year = 2015 and
'NAME' in (player1, player2);

或者如果一个游戏可以多次列出:

select count(distinct gameid)
from RESULTS_TABLE
where comp = 'COMP' and year = 2015 and
'NAME' in (player1, player2);

仅当您需要查询结果以及返回的行数时才使用SQL_CALC_FOUND_ROWS正常使用是应用程序中的分页。

否则,您将返回表中的所有数据,而不仅仅是计数,这可以在 SQL 中轻松计算。

编辑:

对于对手总数,计算非常相似:

select count(distinct (case when player1 = 'NAME' then player2
else player1 end)) as NumOpponents
from RESULTS_TABLE
where comp = 'COMP' and year = 2015 and
'NAME' in (player1, player2);

您甚至可以在同一查询中获取游戏数量和对手数量。

关于MYSQL 从函数返回行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31358032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com