use strict; my $sth_null = $dbh->prepare(q{ SELECT id, name FROM category WHERE parent IS NULL }); $sth->execute or die $dbh->errstr; my $sth_parent = $dbh->prepare(q{ SELECT id,name FROM category WHERE parent = ? }); while ( my @slog = $sth_null->fetchrow_array ) { $sth_parent->execute($slog[0]) or die $dbh->errstr; my $rv = $sth_parent->rows; my $subs = $rv; ...