简体   繁体   English

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

[英]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.

相关问题 仅选择一行具有一对多关系表的最大字段 - Select only one row with max field with One-Many Relationship Table 如何 SELECT 一个字段形成一个表,该表是另一个表的一个字段中包含的字符串的一部分? - How to SELECT one field form one table which is part of string contained in one field of another table? 查询以根据一个字段的最大值和另一字段的特定值查找数据 - query to find data based on max of one field and specific value of another 选择从字段3到字段4的唯一行 - SELECT unique row from field 3 to field 4 MySQL中嵌套的select语句用于根据另一个字段的最大值更新字段会产生错误 - Nested select statement in MySQL for updating field based upon max value of another field gives error 如何选择栏位,但最多先过滤另外1个或2个其他字段 - How to select field but filter 1 or 2 other filed max first 依赖于另一个字段的 select2 字段 - select2 field that depends on another field 按一个自定义字段值排序,并使用Wordpress从另一个字段中选择帖子 - Order by One Custom Field Value and Select Posts From Another With Wordpress PHP中的SQL SELECT MAX(字段)问题 - SQL in PHP Issue with SELECT MAX(field) MySQL-如何选择主键多次出现并且至少另一个字段匹配的行? - MySQL - how to select rows where a primary key occurs more than once AND at least one of another field matches?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM