MySQL 8.0 参考手册  / 第 3 章教程  / 3.6 常见查询示例  /  3.6.4 拥有某列分组最大值的行

3.6.4 拥有某列分组最大值的行

任务:对于每件商品,找到价格最贵的经销商或经销商。

这个问题可以用像这样的子查询来解决:

SELECT article, dealer, price
FROM   shop s1
WHERE  price=(SELECT MAX(s2.price)
              FROM shop s2
              WHERE s1.article = s2.article)
ORDER BY article;

+---------+--------+-------+
| article | dealer | price |
+---------+--------+-------+
|    0001 | B      |  3.99 |
|    0002 | A      | 10.99 |
|    0003 | C      |  1.69 |
|    0004 | D      | 19.95 |
+---------+--------+-------+

前面的示例使用了一个相关子查询,这可能是低效的(请参阅第 13.2.10.7 节,“相关子查询”)。解决该问题的其他可能性是在FROM子句或 LEFT JOIN.

不相关的子查询:

SELECT s1.article, dealer, s1.price
FROM shop s1
JOIN (
  SELECT article, MAX(price) AS price
  FROM shop
  GROUP BY article) AS s2
  ON s1.article = s2.article AND s1.price = s2.price
ORDER BY article;

LEFT JOIN:

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

LEFT JOIN工作原理是当 s1.price为最大值时,没有 s2.price更大的值,因此对应的s2.article值为 NULL。请参阅第 13.2.9.2 节,“JOIN 子句”