Perl DBI/PostgreSQL 最小函数

Perl DBI/PostgreSQL min function

我正在使用 Perl DBI/PostgreSQL,我想检索列中的最小值,但我收到以下代码的 'Use of uninitialized value $id in concatenation (.) or string' 消息:

my $id = 0;
$sth = $dbh->prepare("
    select min(col_id)
    from table
    where col_num = x
") or die $dbh->errstr;
$sth->execute() or die $dbh->errstr;
while (my $results = $sth->fetchrow_hashref) {
    $id = $results->{col_id};
}
print "$id";

它在 postgresql 编辑器中有效,但在 perl 中无效。任何帮助将不胜感激!

您的问题是您的结果集中没有 col_id 列。您正在计算 min(col_id),因此 $results 将有一个 min 键,而不是 col_id 键。你想说:

$id = $results->{min};

提取您要查找的值。或者您可以在 SELECT:

中添加一个别名
$sth = $dbh->prepare("
    select min(col_id) as min_col_id
    from table
    where col_num = x
") or die $dbh->errstr;

并在查看 $results 时使用该名称:

$id = $results->{min_col_id};