使用 LIMIT 函数是子查询

Using LIMIT function is subquery

我正在使用这个查询:

select city, length(city) 
from station 
where length(city) = (select max(length(city)) from station ) 
   OR length(city) = (select min(length(city)) from station) 
order by city asc;

当我将 LIMIT 函数添加到我的子查询时,因为我只需要一个结果 select:

select city, length(city) 
from station 
where length(city) = (select max(length(city)) from station limit 1) 
   OR length(city) = (select min(length(city)) from station limit 1) 
order by city asc;

然后我得到了错误 -

ORA-00907: missing right parenthesis 

任何知道我在该功能上哪里出错的人。我使用 Oracle,我尝试使用 rownum 但它没有帮助。

当您使用 max() 时,则不需要 limit :

select city, length(city) 
from station 
where length(city) = (select max(length(city)) 
                      from station
                     ) OR 
      length(city) = (select min(length(city)) 
                      from station 
                     ) 
order by city asc;

但是,limit 将不支持 Oracle

Oracle 不支持 limi [n]t 语法。等效项是 fetch first [n] rows only(从 Oracle 12c 开始可用)。

但最重要的是:每个子查询都保证 return 只有一条记录,因此不需要 limit.

我进一步建议重写查询以使用 rank(),这避免了对多个子查询的需要,并且在我看来,使逻辑更清晰:

select city, length_city
from (
    select 
        city, 
        lenght(city) length_city,
        rank() over(order by length(city)) rn_asc,
        rank() over(order by length(city) desc) rn_desc
    from station
) t
where rn_asc = 1 or rn_desc = 1

如果您想要 top/bottom 个并列并且只想要其中一个,那么您可以在排名函数中添加一个额外的排序标准:例如,order by length(city), city 给您第一个城市,按字母顺序排列,以防重复。