Perl and MySQL - Return a field from last row of a table using DBI possibly with last_insert_id?

StackOverflow https://stackoverflow.com/questions/10620438

Вопрос

I am trying to return a members firstname field from the table users from the last row of users.

 my $dbh = DBI->connect($dsn, $db_user_name, $db_password) or die "$DBI::errstr";
    my $LastID = $dbh->last_insert_id(`firstname`); ##but I want from table users
    print qq~$LastID~;

This error is returned from above:

DBI last_insert_id: invalid number of arguments: got handle + 0, expected handle + between 4 and 5
Usage:    $h->last_insert_id($catalog, $schema, $table_name, $field_name [, \%attr ])

So, what would be the "best" way (best being best for server, fastest, least memory, load, least amount of overhead.. whatever) to get the field firstname from the last row in the table users?

Realize my example above is not to be taken seriously as I have no idea how to do this without just doing something like my crude, but functional: (p.s. UserID is NOT assigned by auto increment but, is in numeric order and a new user gets a higher UserID. Just the way this was when I tackled the pre existing problem.)

my $dbh = DBI->connect($dsn, $db_user_name, $db_password) or die "$DBI::errstr";
my $dsn = $dbh->prepare(qq{SELECT `firstname` FROM `users` ORDER BY ABS(UserID) DESC LIMIT ?,?});
$dsn->execute('1','1') or die "$DBI::errstr";
while(@nrow = $dsn->fetchrow_array()) {
$firstname = $nrow[0];
}

I assumed since I was using DBI that may provide the best solution but, I am inexperienced obviously and need some advice and guidance to learn the proper way to do this. Thanks for any assistance.

Это было полезно?

Решение

You mention that UserID is not auto incrementing, so I'm not sure if last_insert_id will work in this situation. It may, but I'm just not sure. The document states:

Typically this would be a value assigned by the database server to a column with an auto_increment or serial type.

I would look to solve this by just using a SQL statement:

SELECT
    u.firstname
FROM
    users u
JOIN
    (
    SELECT
        MAX(UserID) AS UserID
    FROM
        users
    ) t ON u.UserID = t.UserID

The code with DBI would then look like this:

my $stmt = 'SELECT u.firstname FROM users u JOIN(SELECT MAX(UserID) AS UserID FROM users) t ON u.UserID = t.UserID';
my $first_name = ($dbh->selectrow_array($stmt))[0];

Другие советы

last_insert_id method takes 4 args. Use like this:

  my $id = $connection->last_insert_id(undef, 'myschemaname', 'mytablename', 'mycolumnname');

See the DBI pod.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top