This question already has answers here:
SQL query to check if a name begins and ends with a vowel
                                
                                    (21个回答)
                                
                        
                                在8个月前关闭。
            
                    
目的是查询所有以字母开头和结尾为元音的城市。我尝试了下面的似乎无效的代码。你能解释为什么它不起作用吗?有没有更好的办法?

我尝试首先获取以元音结尾的城市,然后尝试将其用作选择以元音开头的城市的子查询,如下所示

我已经尝试实现此代码:

SELECT DISTINCT(CITY)
FROM STATION
WHERE CITY LIKE 'a%'
  OR CITY LIKE 'e%'
  OR CITY LIKE 'i%'
  OR CITY LIKE 'o%'
  OR CITY LIKE 'u%'
AND CITY IN (
  SELECT DISTINCT(CITY)
  FROM STATION
  WHERE CITY LIKE '%a'
    OR CITY LIKE '%e'
    OR CITY LIKE '%i'
    OR CITY LIKE '%o'
    OR CITY LIKE '%u'
);


所需的输出如下所示:

Oslo
Upperco
Amazonia
...
...
...


我得到的是这些输出以及不以元音结尾的城市,例如:

Arlington
Albany
Upperco
Aguanga
Odin
East China
Algonac
Onaway
Irvington
Arrowsmith
Oakfield
Elkton
East Irvine
Amo
...
...
...

最佳答案

更好的方法可能是使用REGEXP

SELECT DISTINCT CITY
FROM STATION
WHERE CITY REGEXP '^[aeiou].*[aeiou]$';


请注意,REGEXP不区分大小写,因此我们只需要在正则表达式的单个情况下使用[aeiou]

您当前的查询实际上在逻辑上是正确的,但由于对ANDOR的使用/理解不正确,因此不会为您提供所需的行为。 AND的优先级高于OR,因此您在查询中缺少一些括号。试试这个版本:

SELECT DISTINCT CITY
FROM STATION
WHERE
    (LOWER(CITY) LIKE 'a%' OR
     LOWER(CITY) LIKE 'e%' OR
     LOWER(CITY) LIKE 'i%' OR
     LOWER(CITY) LIKE 'o%' OR
     LOWER(CITY) LIKE 'u%') AND
    (LOWER(CITY) LIKE '%a' OR
     LOWER(CITY) LIKE '%e' OR
     LOWER(CITY) LIKE '%i' OR
     LOWER(CITY) LIKE '%o' OR
     LOWER(CITY) LIKE '%u') ;

10-08 01:50