8.4 中文镜像

MySQL 8.4 参考手册 · 中文镜像

正文为中文,英文原文默认隐藏。点击任意中文段落即可展开 / 收起对应英文原文。

打开官方英文原文 ↗

译文由机器翻译生成,仅供理解参考;有疑问请以官方英文原文为准。

MySQL 8.4 参考手册 / 5 教程 / 5.6 常见查询示例 / 5.6.2 保存某一列最大值的行
中文点击中文段落可显示 / 隐藏英文原文本页译文覆盖 100%

5.6.2 某一列最大值所在的行5.6.2 The Row Holding the Maximum of a Certain Column

任务:找出最昂贵商品的编号、经销商和价格。Task: Find the number, dealer, and price of the most expensive article.

这可以通过子查询轻松完成:This is easily done with a subquery:

SELECT article, dealer, price
FROM   shop
WHERE  price=(SELECT MAX(price) FROM shop);

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|    0004 | D      | 19.95 |
+---------+--------+-------+

另一种解决方案是使用 LEFT JOIN,如下所示:Another solution is to use a LEFT JOIN, as shown here:

SELECT s1.article, s1.dealer, s1.price
FROM shop s1
LEFT JOIN shop s2 ON s1.price < s2.price
WHERE s2.article IS NULL;

你也可以通过按价格降序排序所有行,然后使用 MySQL 特有的 LIMIT 子句只获取第一行,方法如下:You can also do this by sorting all rows descending by price and get only the first row using the MySQL-specific LIMIT clause, like this:

SELECT article, dealer, price
FROM shop
ORDER BY price DESC
LIMIT 1;
Note

如果有几篇最贵的文章,每篇价格为 19.95,LIMIT 解决方案只会显示其中一篇。If there were several most expensive articles, each with a price of 19.95, the LIMIT solution would show only one of them.