mysql查询在perl和mysql中执行了不同的结果

时间:2013-09-30 03:35:54

标签: mysql perl dbi

我尝试按照这个帖子SQL Limit results per column value来显示每个分支的前10个,但我在Perl中编写查询时遇到了麻烦。

如果我在MYSQL Front中运行查询,它会根据金额产生每个分支的前10名。 但是当我使用DBI模块将查询放入Perl时,它会产生所有行。我的Perl脚本有什么问题吗?

Mysql查询:

select name, branch, amount from (select name, branch, amount, if(@mainbranch = branch, @num := @num + 1, (@num := 0 || @mainbranch := branch)) as num from branch_amount where branch in (102, 106, 0 ) order by branch, amount desc ) a where num<=10

Perl脚本:

use DBI;
my $db=DBI->connect("DBI:mysql:$database;host=$host;user=$user;password=$passwd")
my $query = "select name, branch, amount from (select name, branch, amount, if(\@mainbranch = branch, \@num := \@num + 1, (\@num := 0 || \@mainbranch := branch)) as num from branch_amount where branch in (102, 106, 0 ) order by branch, amount desc ) a where num<=10";
$db->prepare("$query");
$sth->execute() or die "$query";

我尝试从Perl Script中计算结果,并且所有行的num字段值都是1。我建议if内的操作不起作用,但我不知道为什么以及如何。所有帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

在准备帮助之前把它放在哪里?

$db->do('set @num=-1');
$db->do('set @mainbranch=-1');