MySQL查询最短路径&;字段的最长长度 问题

MySQL查询最短路径&;字段的最长长度 问题,mysql,aggregate-functions,Mysql,Aggregate Functions,我需要从数据库中返回最短和最长的城市名称及其各自的长度。我还欢迎对这个查询进行改进,使其更加优雅 SQL小提琴 到目前为止,我有一个示例数据库和查询: 查询 当前结果 期望结果 我会使用union all、order by和limit来实现这一点。如果您只需要一个最长和最短名称的示例: (select city, length(city) from station order by length(city) asc limit 1 ) union all (select city, le

我需要从数据库中返回最短和最长的城市名称及其各自的长度。我还欢迎对这个查询进行改进,使其更加优雅

SQL小提琴 到目前为止,我有一个示例数据库和查询:

查询 当前结果 期望结果
我会使用
union all
order by
limit
来实现这一点。如果您只需要一个最长和最短名称的示例:

(select city, length(city)
 from station
 order by length(city) asc
 limit 1
) union all
(select city, length(city)
 from station
 order by length(city) desc
 limit 1
);
如果你想要平局,当多个城市比赛时,我会:

select s.city, length(s.city)
from station s cross join
     (select max(length(city)) as maxl, min(length(city)) as minl
      from station
     ) ss
where length(s.city) in (ss.minl, ss.maxl);

reus怎么了?第一个按字母顺序排列的是最短的胜利。我想hackerrank把你带到这里来了戈登:第一个查询有效,但第二个输出Dole 4 | Sant'Egidio del Monte Albino 28 | reus 4草莓还是戈登:join比union all效率高还是低?@techsmi扳手比锤子效率高?它们是用于不同事物的不同工具。也就是说,您可以自己测试哪个查询最快,只要在这里提问就可以了。我的钱在GL的第一个解决方案上-但我可能不对。@techmsi。有两个城市的名字最短。“Dole”和“Reus”。第二个是正确的。@我确实测试了它们&GL的第一个&您的解决方案根据sqlfiddle需要1ms,所以这就是我问的原因。我并不感到惊讶;-)哈哈。是的,我在中添加了这条评论,因为当其他人得到这个答案时,他们会知道哪些解决方案有效,哪些不有效。
Dole    4
Sant'Egidio del Monte Albino    28
(select city, length(city)
 from station
 order by length(city) asc
 limit 1
) union all
(select city, length(city)
 from station
 order by length(city) desc
 limit 1
);
select s.city, length(s.city)
from station s cross join
     (select max(length(city)) as maxl, min(length(city)) as minl
      from station
     ) ss
where length(s.city) in (ss.minl, ss.maxl);
select min(a.city),length(a.city)
from station a
join (SELECT min(length(city)) minlength,max(length(city)) maxlength from station) b
on length(a.city) in (minlength,maxlength)
group by length(a.city)