如何使用 LIKE 编写查询也接受特殊字符?

How to write query using LIKE to accept special characters also?

我在数据库中有一个值为“123-456-789”。我的查询是

SELECT * FROM table_name WHERE phone LIKE "%123456789%"

但是没有给出结果。任何想法

当然,你排除了破折号所以它与中间部分不匹配。你查询的逻辑是 "anything before my string and anything after" 但中间部分应该是一样的。

SELECT * FROM table_name WHERE phone LIKE "%123-456-789%"  

这会起作用。

但是如果你想排除破折号,你可以这样做:

SELECT * FROM table_name WHERE REPLACE(phone ,'-','') = "123456789"  

如果您的输入还包括破折号,那么您也可以将它们删除:

SELECT * FROM table_name WHERE REPLACE(phone ,'-','') = REPLACE('123456789','-','')

这样您就可以搜索带破折号或不带破折号的数字,但永远不会考虑破折号。

尝试

SELECT * FROM table_name WHERE `phone` LIKE '%[0-9]' '_' '[0-9]' '_' [0-9]%'

您也可以考虑一些 OR 语句

SELECT * FROM table_name WHERE `phone` LIKE '%[0-9]' '_' '[0-9]' '_' [0-9]%' OR '%[0-9]%'

您可以像这样尝试在 mySQL 中直接使用 regex

select * from `table_name` where `phone` regexp '[0-9]{3}-[0-9]{3}-[0-9]{3}';