了解为什么在开始和结束时查询带有元音的城市不起作用
Understanding why querying cities with vowels at start and end doesnt work
任务:
查询 table 中第一个和最后一个字符都是元音的名字列表 [重复]。
我想从 table STATION(id,city, longitude, latitude) 查询城市名称列表,它们的第一个和最后一个字符都是元音。结果不能包含重复项。
我的查询:
SELECT DISTINCT CITY
FROM STATION
WHERE CITY LIKE '[aeiou]%' AND '%[aeiou]'
我找到了这个解决方案:
Select distinct city
from station
Where regexp_like(city, '^[aeiou].*[aeiou]$','i');
为什么我的查询不起作用?
'[aeiou]'
是一个正则表达式字符 class,运算符 LIKE
不支持它。因此,您的查询不会按照您的预期进行:它实际上搜索以 '[aeiou]'
开头的 乱码字符串 (即使是,您也需要重复表达式 city like ...
两次:city like ... and ...
也没有达到您的预期。
您找到的解决方案使用 regexp_like()
和以下正则表达式:^[aeiou].*[aeiou]$
,这意味着:
^ beginning of the string
[aeiou] one of the characters in the list
.* a sequence of 0 to N characters
[aeiou] one of the characters in the list
$ end of the string
选项 'i'
使搜索不区分大小写。
这可行,但需要 MySQL 8.0。如果您是 运行 早期版本,请考虑使用 REGEXP
条件:
CITY REGEXP '^[aeiou].*[aeiou]$'
任务:
查询 table 中第一个和最后一个字符都是元音的名字列表 [重复]。
我想从 table STATION(id,city, longitude, latitude) 查询城市名称列表,它们的第一个和最后一个字符都是元音。结果不能包含重复项。
我的查询:
SELECT DISTINCT CITY
FROM STATION
WHERE CITY LIKE '[aeiou]%' AND '%[aeiou]'
我找到了这个解决方案:
Select distinct city
from station
Where regexp_like(city, '^[aeiou].*[aeiou]$','i');
为什么我的查询不起作用?
'[aeiou]'
是一个正则表达式字符 class,运算符 LIKE
不支持它。因此,您的查询不会按照您的预期进行:它实际上搜索以 '[aeiou]'
开头的 乱码字符串 (即使是,您也需要重复表达式 city like ...
两次:city like ... and ...
也没有达到您的预期。
您找到的解决方案使用 regexp_like()
和以下正则表达式:^[aeiou].*[aeiou]$
,这意味着:
^ beginning of the string
[aeiou] one of the characters in the list
.* a sequence of 0 to N characters
[aeiou] one of the characters in the list
$ end of the string
选项 'i'
使搜索不区分大小写。
这可行,但需要 MySQL 8.0。如果您是 运行 早期版本,请考虑使用 REGEXP
条件:
CITY REGEXP '^[aeiou].*[aeiou]$'