[英]How to select one row with max(select field) and another (specific field)?
How to select one row with max(select field) and another (specific field)? 如何选择具有max(选择字段)和另一(特定字段)的一行?
Below is my code 下面是我的代码
1. Get to know max(select field) first 1.首先了解max(选择字段)
2. Then select all field within the row. 2.然后选择该行内的所有字段。 but step 2 doesn't return any thing, wonder know why? 但是第2步没有返回任何东西,想知道为什么吗?
And is there shorter syntax for same result?? 并且有较短的语法用于相同的结果吗?
Thanks. 谢谢。
$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);
You could do it in one step with this query: 您可以使用此查询一步完成此操作:
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.