Task: For each article, find the dealer or dealers with the most expensive price.任务:针对每件商品,找到价格最贵的经销商。
This problem can be solved with a subquery like this one:这个问题可以通过如下子查询解决:
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 | +---------+--------+-------+
The preceding example uses a correlated subquery, which can be inefficient (see Section 13.2.11.7, “Correlated Subqueries”). 前面的例子使用了一个相关的子查询,这可能是低效的(参见第13.2.11.7节,“相关子查询”)。Other possibilities for solving the problem are to use an uncorrelated subquery in the 解决这个问题的其他可能性是在FROM
clause, a LEFT JOIN
, or a common table expression with a window function.FROM
子句中使用不相关的子查询、LEFT JOIN
或带有窗口函数的公共表表达式。
Uncorrelated subquery:不相关子查询:
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;
The LEFT JOIN
works on the basis that when s1.price
is at its maximum value, there is no s2.price
with a greater value and thus the corresponding s2.article
value is NULL
. LEFT JOIN
的工作原理是,当s1.price
处于其最大值时,不存在具有更大值的s2.price
,因此相应的s2.article
值为NULL
。See Section 13.2.10.2, “JOIN Clause”.请参阅第13.2.10.2节,“JOIN子句”。
Common table expression with window function:带有窗口函数的通用表表达式:
WITH s1 AS ( SELECT article, dealer, price, RANK() OVER (PARTITION BY article ORDER BY price DESC ) AS `Rank` FROM shop ) SELECT article, dealer, price FROM s1 WHERE `Rank` = 1 ORDER BY article;