SQL query to check if a name begins and ends with a vowel

后端 未结 25 1091
臣服心动
臣服心动 2020-11-30 23:16

I want to query the list of CITY names from the table STATION(id, city, longitude, latitude) which have vowels as both their first and last charact

25条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 00:11

    Use a regular expression.

    WHERE name REGEXP '^[aeiou].*[aeiou]$'
    

    ^ and $ anchor the match to the beginning and end of the value.

    In my test, this won't use an index on the name column, so it will need to perform a full scan, as would

    WHERE name LIKE 'a%a' OR name LIKE 'a%e' ...
    

    I think to make it use an index you'd need to use a union of queries that each test the first letter.

    SELECT * FROM table
    WHERE name LIKE 'a%' AND name REGEXP '[aeiou]$'
    UNION
    SELECT * FROM table
    WHERE name LIKE 'e%' AND name REGEXP '[aeiou]$'
    UNION
    SELECT * FROM table
    WHERE name LIKE 'i%' AND name REGEXP '[aeiou]$'
    UNION
    SELECT * FROM table
    WHERE name LIKE 'o%' AND name REGEXP '[aeiou]$'
    UNION
    SELECT * FROM table
    WHERE name LIKE 'u%' AND name REGEXP '[aeiou]$'
    

提交回复
热议问题