gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:32:11 24 4
gpt4 key购买 nike

我有一个接受投票的小型系统,在我的查询中,我选择投票(用户名)和该用户的总票数。我的想法是只显示拥有更多选票的用户,我知道我可以添加 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/

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