0

因此,我正在使用的以下查询产生 4 行:

SELECT 
  `DMV`.`id` AS `dmvID`,
  `D`.`id` AS `documentID`,
  `DMV`.`name` AS `documentName`,
  `U`.`username` AS `creatorUserName`,
  `D`.`folder_id` AS `folderID`,
  `D`.`created` AS `createDate`,
  `SL`.`name` AS `statusName`,
  `UM`.`username` AS `modifiedUserName`,
  `DMV`.`version_created` AS `modifiedDate`,
  `UO`.`username` AS `ownerUserName`,
  `DTL`.`name` AS `documentTypeName` 
FROM 
  `document_metadata_version` `DMV`
  LEFT JOIN `documents` `D` 
    ON `DMV`.`document_id` = `D`.`id`
  LEFT JOIN `users` `U` 
    ON `D`.`creator_id` = `U`.`id`
  LEFT JOIN `users` `UM` 
    ON `D`.`modified_user_id` = `UM`.`id`
  LEFT JOIN `users` `UO` 
    ON `D`.`owner_id` = `UO`.`id`
  LEFT JOIN `status_lookup` `SL` 
    ON `D`.`status_id` = `SL`.`id`
  LEFT JOIN `document_types_lookup` `DTL` 
    ON `DMV`.`document_type_id` = `DTL`.`id`
WHERE
    DMV.document_id = 543433
;

为简洁起见,我将省略所有与手头问题无关的不相关字段。dmvIDdocumentTypeName(第一列和最后一列)的结果是:

+--------+------------------+
| dmvID  | documentTypeName |
+--------+------------------+
| 566053 | Default          |
| 566183 | Default          |
| 681391 | ASCO Documents   |
| 681411 | ASCO Documents   |
+--------+------------------+

我只对最后一行感兴趣,所以很自然,我将修改 SELECT 语句以在 MAX() 上使用dmvID

SELECT 
  MAX(`DMV`.`id`) AS `dmvID`,
# Rest of query unchanged

返回:

+--------+------------------+
| dmvID  | documentTypeName |
+--------+------------------+
| 681411 | Default          |
+--------+------------------+

从上面注意到,681411 实际上是 MAX(),但关联documentTypeName不是dmvID681411 的等效值,我假设它与dmvID566053 匹配。我如何让它返回:

+--------+------------------+
| dmvID  | documentTypeName |
+--------+------------------+
| 681411 | ASCO Documents   |
+--------+------------------+
4

1 回答 1

3

如果您只需要该列中具有最高值的单行,请使用 ORDER BY 和 LIMIT 1(而不是使用 MAX() 的聚合查询)。

...
WHERE
DMV.document_id = 543433
ORDER BY dmvID DESC
LIMIT 1;
于 2012-07-05T16:33:37.177 回答