1

如何选择具有 max(选择字段)和另一行(特定字段)的行?

下面是我的代码
1. 首先了解 max(select field)
2. 然后选择行内的所有字段。但是第2步没有返回任何东西,不知道为什么?
相同结果是否有更短的语法?
谢谢。

$gid = 1;

// get lid
$sth = $db->prepare("SELECT MAX(lid) as lid FROM t WHERE gid = :gid");
$sth->bindParam(':gid', $gid);
$sth->execute();
$arr = $sth->fetch(PDO::FETCH_ASSOC);
print $arr['lid'];

// nothing return??
$lid = $arr['lid'];
$sth = $db->prepare("SELECT * FROM t WHERE gid = :gid AND lid = :lid");
$sth->bindParam(':gid', $gid);
$sth->bindParam(':lid', $lid);
$row = $sth->fetch();
print_r($row);
4

1 回答 1

0

您可以使用以下查询一步完成:

$sql = "SELECT t.* 
        FROM t 
        INNER JOIN (
            SELECT MAX(lid) as lid 
            FROM t 
            WHERE gid = :gid
        ) AS x ON t.lid = x.lid";
$sth = $db->prepare($sql);
$sth->bindParam(':gid', $gid);
$sth->execute();
$arr = $sth->fetch(PDO::FETCH_ASSOC);
print_r($arr);
于 2013-07-20T13:09:07.527 回答