简体   繁体   中英

Perl DBI/PostgreSQL min function

I'm using Perl DBI/PostgreSQL, and I want to retrieve a minimum value in a column but I get a 'Use of uninitialized value $id in concatenation (.) or string' message for the following code:

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";

It works in the postgresql editor, but not in perl. Any help will be appreciated!

Your problem is that there is no col_id column in your result set. You're computing min(col_id) so $results will have a min key, not a col_id key. You want to say:

$id = $results->{min};

to extract the value you're looking for. Or you could add an alias in your SELECT:

$sth = $dbh->prepare("
    select min(col_id) as min_col_id
    from table
    where col_num = x
") or die $dbh->errstr;

and use that name when looking at $results :

$id = $results->{min_col_id};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM