mysql - 如何从数据库中选择得票最多的用户?

标签 mysql sql perl cgi

我有一个接受投票的小型系统,在我的查询中,我选择投票(用户名)和该用户的总票数。 我的想法是只显示拥有更多选票的用户,我知道我可以添加 ORDER BY 的查询并获得第一个值,该值将是票数最高的那个。 但是我正在尝试确定两个人是否有票数。我该怎么做?

我正在使用 cgi。

my $connection = $MY_CONNECTION->prepare("SELECT voto, COUNT(*) total FROM votos  WHERE mes = 12 GROUP BY vote HAVING COUNT(*) > 0 ORDER BY COUNT(*)");
$connection->execute || print "ERROR 1";

my @resultados;
my $info = '';


while ($info = $connection->fetchrow_hashref()) {

    my $nombre   = $info->{voto};
    my $totalVotos = $info->{total};

my $winner = "";
my $temp2  = "";
my $temp   = $totalVotos ;

if ($temp2 => $temp) {
    $temp2 = $totalVotos ;
    $winner = $nombre   ; 

}


    print "<p><strong>Winner: </strong> $winner </p> "; 
    print "<hr>";
}

最佳答案

您可以通过以下方式返回获得最高票数(以及多少票)的所有人:

select voto, count(*) as total from votos
    where mes = 12
    group by voto -- I assume "vote" in your question was typo
    having total = (
        select max(ct) from (
            select voto,count(*) as ct from votos group by voto
        )
    )
    and total > 0 -- from your original but not sure it can fail
;

您也可以使用 rank() 函数。


在不修改 SQL 的情况下,您可以将 perl 更改为如下内容:

# ...

# initialisation shouldn't be inside while loop
my $winner = "";
my $temp2  = "";

while ($info = $connection->fetchrow_hashref()) {
    my $nombre = $info->{voto};
    my $totalVotos = $info->{total};

    if ($temp2 < $totalVotos) { # your original "=>" seems wrong
        $temp2 = $totalVotos;
        @winner = $nombre;
    elsif ($temp2 == $totalVotos) {
        push @winner, $nombre;
    }
}

# postprocessing shouldn't be inside while loop
$winner = join(", ", @winner); # or whatever
print "<p><strong>Winner: </strong> $winner </p> "; 
print "<hr>";

关于mysql - 如何从数据库中选择得票最多的用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925106/

相关文章:

python - Django 时区与 mysql 插入错误

mysql - 当查询没有任何行时显示默认记录

mysql - MySQL 中变量的意外行为

php - 如何从mysql数据创建图表? (使用谷歌可视化 API)

sql在一对多关系中创建 View

sql - 不将查询存储为字符串的动态数据透视查询

sql - Flyway:无法在 'installed_on' 中插入值 NULL,表 'schema_version' 列不允许为空。插入失败

perl - 如何在 perl 中逐行将命令的输出存储在数组中?

perl - 两个日期之间的天/月/年

perl - Perl 中的 Microsoft OneDrive API 客户端无法获取访问 token