MySQL查询最短和最短最长的一个字段

时间:2016-08-01 00:30:00

标签: mysql aggregate-functions

问题

我需要退回最短的&最长的 city 名称及其各自的数据库长度。我也欢迎对此查询进行改进,以使其更加优雅。

SQL小提琴

我有一个示例数据库&查询到目前为止: http://sqlfiddle.com/#!9/3b4a7c/1/0

查询

SELECT DISTINCT City, LENGTH(City) as len
FROM STATION
WHERE LENGTH(City)=(SELECT MIN(LENGTH(City)) FROM STATION) 
OR LENGTH(City)=(SELECT MAX(LENGTH(City)) FROM STATION)
ORDER BY len

当前结果

Dole    4
Reus    4
Sant'Egidio del Monte Albino    28

期望结果

Dole    4
Sant'Egidio del Monte Albino    28

2 个答案:

答案 0 :(得分:6)

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)

答案 1 :(得分:2)

我会使用union allorder bylimit执行此操作。 。 。如果您只想要一个最长和最短名称的例子:

(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);