MySQL LIKE with range doesn't work

▼魔方 西西 提交于 2019-11-28 02:21:39

You write:

It seems that there's something wrong with range syntax here

Indeed so. MySQL's LIKE operator (and SQL generally) does not support range notation, merely simple wildcards.

Try MySQL's nonstandard RLIKE (a.k.a. REGEXP), for fuller-featured pattern matching.

I believe LIKE is just for searching for parts of a string, but it sounds like you want to implement a regular expression to search for a range.

In that case, use REGEXP instead. For example (simplified):

SELECT * FROM mytable WHERE name REGEXP "[a-z]"

Your current query is looking for a string of literally "[a-z]".

Updated:

SELECT
CAST(t.date AS DATE) AS 'date',
COUNT(*) AS total,
SUM(LENGTH(LTRIM(RTRIM(t.name))) > 4 
    AND (LOWER(t.name) REGEXP '%[a-z]%')) AS 'n'
FROM
mytable t
GROUP BY 
CAST(t.date AS DATE)

I believe you want to use WHERE REGEXP '^[a-z]$' instead of LIKE.

You have regex in your LIKE statement, which doesn't work. You need to use RLIKE or REGEXP.

SELECT CAST(t.date AS DATE) AS date,
    COUNT(*) AS total
FROM mytable AS t
WHERE t.name REGEXP '%[a-zA-Z]%' 
GROUP BY CAST(t.date AS DATE)
HAVING SUM(LENGTH(LTRIM(RTRIM(t.name))) > 4

Also just FYI, MySQL is terrible with strings, so you really should trim before you insert into the database. That way you don't get all that crazy overhead everytime you want to select.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!