【问题标题】:How to query for city name as well as length of the smallest city name from the same table如何从同一张表中查询城市名称以及最小城市名称的长度
【发布时间】:2020-05-28 19:42:11
【问题描述】:

我的代码是这样的,但给出了错误,不知道为什么。请帮忙!

select city, 
       min(length(city)) 
from station 
group by length(city)=min(length(city)) 
order by city asc;

【问题讨论】:

  • 而错误是...?
  • 错误是:组函数的使用无效
  • 也许可以解释一下你想用那个 group by 语句来完成什么?看起来您正在混淆 GROUP BY 和 WHERE 语句
  • 感谢您的见解我终于得到了正确的代码:select city, min(length(city)) as minimum from station group by city order by minimum asc limit 1 ;

标签: mysql sql select sql-order-by greatest-n-per-group


【解决方案1】:

如果你只想要名字最短的城市,你可以简单地order bylimit

select city, char_length(city) city_length
from station
order by city_length
limit 1

这只会返回一行。另一方面,如果您想允许底部关系,那么您可以使用子查询进行过滤,如下所示:

select city, char_length(city) city_length
from station
where char_length(city) = (select min(char_length(city)) from station)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多