【问题标题】:How to use select query inside max function? [duplicate]如何在 max 函数中使用 select 查询? [复制]
【发布时间】:2020-09-15 02:12:07
【问题描述】:
我可以知道以下查询无效的原因吗?
select * from shop where price = max(select price from shop);
我正在尝试获取 shop 表中的最高价格列,因此在 where 子句中我将价格与查询集中的最高价格进行比较。
我知道 max 的语法不允许这样做,但是 max 有什么理由不将查询集作为参数?
【问题讨论】:
标签:
mysql
sql
group-by
subquery
max
【解决方案1】:
等式右边的表达式无效。 max() 是一个聚合函数,需要 selected。那将是:
select * from shop where price = (select max(price) from shop);
这会为您提供shop 中具有顶部price 的行,并包括平局(如果有)。
请注意,如果您不需要允许顶部关系,则可以将查询简化如下:
select * from shop order by price desc limit 1
【解决方案2】:
你也可以换一种方式:
select * from shop where price = (select max(price) from shop);
【解决方案3】:
为什么这无效?有两个原因:
首先,max() 不允许出现在 where 子句中。其次,您有一个返回多个值的子查询——但是,这是不允许的,即使对于聚合函数也是如此。
max()需要进入子查询,将其变成标量子查询——即返回一列0或1行的子查询:
select s.*
from shop s
where s.price = (select max(s2.price) from shop s2);
如果你只想返回一行,更简单的方法是:
select s.*
from shop s
order by s.price desc
limit 1;