我需要退回最短的&最长的 city 名称及其各自的数据库长度。我也欢迎对此查询进行改进,以使其更加优雅。
我有一个示例数据库&查询到目前为止: 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
答案 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 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);