在子查询中使用MYSQL限制中的变量

时间:2013-08-08 19:41:22

标签: mysql loops limit

我正在尝试重新创建我在mySQL上的SQL服务器中执行的一些代码。我想为表中的每一行插入一行。我使用循环来执行此操作,在SQL服务器中我使用SELECT TOP @foo

这是我的mySQl

    begin
    set @maxloop = (select max(id) from `LeagueInfo`);
    set @loopno = 1;

    while @loopno <= @maxloop DO

SET @mtop = (select `teams` * `homegames` from `LeagueInfo` where id = @loopno);
SET @div = (select `LeagueShortName` from `LeagueInfo` where id = @loopno);
SET @teams = (select teams from `LeagueInfo` where id = @loopno);
SET @homegames = (select homegames from `LeagueInfo` where id = @loopno);


SET @fthgsum = (select sum(`FTHG`)/@teams/@homegames from `footy` where `id` in(select`id`, `div` from `footy`
        where `div` = @DIV
        order by `matchdate` desc LIMIT @mtop));
SET @ftagsum = (select sum(`FTAG`)/@teams/@homegames from `footy` where `id` in(select`id`, `div` from `footy`
        where `div` = @DIV
        order by `matchdate` desc LIMIT @mtop));
insert into `looptable` (`di`, `homeav`, `awayav`) values (@div, @fthgsum,@fthgsum);
        set @loopno = @loopno +1;
   END while;
    END;

我在限制@mtop时遇到错误。我已经读过,我可以用准备好的声明来解决这个问题,但我不确定如何在子查询中做到这一点。有没有做到这一点,还是有另一个是我可以根据该表中每一行的另一个表中的值选择前x行数。

由于 保罗

1 个答案:

答案 0 :(得分:0)

在您的代码行中,

SET @mtop = (select 'teams' * 'homegames' from 'LeagueInfo' where id = @loopno)

mtop不是数字,因为限制必须是数字才是假的。

也许您想使用“count(*)”?