SQL query for finding the longest name and shortest name in a table

后端 未结 29 2056
春和景丽
春和景丽 2021-01-31 00:11

I have a table with one of the columns is of type varchar(city). and want to find the longest and shortest of values stored in that column.

select a.city, a.city         


        
29条回答
  •  逝去的感伤
    2021-01-31 00:23

    You query requires just a few tweaks. The fundamental problem is that you cannot use a in the subquery as you are doing:

    select a.city, a.city_length
    from (select city, char_length(city) city_length 
          from station 
         ) a
    where a.city_length = (select min(char_length(city)) from station) or
          a.city_length = (select max(char_length(city)) from station);
    

    That said, a simpler way to write the query is:

    select s.*
    from station s cross join
         (select min(char_length(city)) as mincl, max(char_length(city)) as maxcl
          from station
         ) ss
    where char_length(s.city) in (mincl, maxcl);
    

提交回复
热议问题