mysql选择唯一项的最大值

时间:2018-08-17 20:12:29

标签: mysql

我有这张桌子,需要用最大长度和最小长度来记录城市。

在此查询中,我试图获取最大长度

http://localhost/project/index.php/vendor/bootstrap/css/bootstrap.min.css

select x.name, x.len from
(select name, char_length(name)  as len
from tutorials.city) x
where x.len = (select max(x.len) from x)

此查询在where子句中与聚合器一起使用-

select x.name, x.len from
(select name, char_length(name)  as len
from tutorials.city) x
where x.len = (select max(id) from tutorials.city)

2 个答案:

答案 0 :(得分:1)

您不能在WHERE子句中使用聚合函数。只有选择了所有行,然后使用WHERE来选择行,聚合才会完成。

您可以改用HAVING

select x.name, x.len from
(select name, char_length(name)  as len
from tutorials.city) x
HAVING x.len = MAX(x.len)

请参见SQL - having VS where

答案 1 :(得分:0)

对于最大长度:

select name
from tutorials.city
order by length(city) desc
limit 1;

最小长度:

select name
from tutorials.city
order by length(city)
limit 1;