提问者:小点点

下面两条mysql语句有什么不同? (mysql文档中某一列的分组最大值)


下面两条mysql语句有什么不同?

select article, dealer, price from shop s1 where price=(select max(**s2.price**) from shop s2
                                                        where s1.article = s2.article)
                                           order by article;
select article, dealer, price from shop s1 where price=(select max(**s1.price**) from shop s2
                                                        where s1.article = s2.article)
                                           order by article;

这两个的查询结果是不一样的,我只是不能理解这两个的不同。 请帮我理解一下,非常感谢。


共1个答案

匿名用户

第二个是相关子查询,但返回的值与外部查询中的s1.price相同。 因为用于内部查询和外部查询的表是相同的,所以它在功能上等同于:

where price is not null and article is not null

也就是说,任何具有有效价格的有效商品都将匹配子查询的结果。

第一个是一个相关子查询,它获取每个商品的最高价格,然后返回外部行。 有了正确的索引,这通常是编写此类查询的最有效的方法。