简体   繁体   English

带有空格的MySQL'LIKE'查询

[英]MySQL 'LIKE' query with spaces

I have a MySQL database with postcodes in it, sometimes in the database there are spaces in the postcodes (eg. NG1 1AB) sometimes there are not (eg. NG11AB). 我有一个带有邮政编码的MySQL数据库,有时在数据库中,邮政编码中有空格(例如NG1 1AB),有时候没有(例如NG11AB)。 Simlarly in the PHP query to read from the database the person searching the database may add a space or not. 同样在PHP查询中从数据库中读取搜索数据库的人可能会添加空格。 I've tried various different formats using LIKE but can't seem to find an effective means of searching so that either end it would bring up the same corresponding row (eg. searching for either NG11AB or NG1 1AB to bring up 'Bob Smith' or whatever the corresponding row field would be). 我尝试过使用LIKE的各种不同的格式,但似乎找不到有效的搜索方式,这样任何一端都会产生相同的相应行(例如,搜索NG11AB或NG1 1AB来调出'Bob Smith'或者相应的行字段是什么)。

Any suggestions? 有什么建议么?

I wouldn't even bother with LIKE or regex and simply remove spaces and compare the strings: 我甚至不打扰LIKE或正则表达式,只需删除空格并比较字符串:

SELECT *
FROM mytable
WHERE LOWER(REPLACE(post_code_field, ' ', '')) = LOWER(REPLACE(?, ' ', ''))

Note that I also convert both values to lower case to still match correctly if the user enters a lower-case post code. 请注意,如果用户输入小写后置代码,我还会将两个值都转换为小写,以便仍然正确匹配。

SELECT *
FROM MYTABLE
WHERE REPLACE(MYTABLE.POSTCODE, ' ', '') LIKE '%input%'

Make sure your PHP input is trimmed as well 确保您的PHP输入也被修剪

Assuming your column has more than just the postcode in it: Remove all spaces before doing the like test: 假设您的列中不仅包含邮政编码:在执行类似测试之前删除所有空格:

where replace(postcode, ' ', '') like '%NG11AB%'

If your columns has just the postcode in it: 如果您的列中包含邮政编码:

where replace(postcode, ' ', '') = 'NG11AB'

or 要么

where postcode like 'N%G%1%1%A%B'

Regex will work for both cases. 正则表达式将适用于这两种情况。 The following regex allows optional spaces between each letter: 以下正则表达式允许每个字母之间的可选空格:

where postcode rlike 'N ?G ?1 ?1 ?A ?B' -- use regex

You can use "*" metacharacter who matches 0 or more char, eg 您可以使用匹配0或更多字符的"*"元字符,例如
LIKE "NG1*1AB" 像“NG1 * 1AB”
matches NG11AB and NG1 1AB 匹配NG11AB和NG1 1AB
More examples: http://www.shayanderson.com/mysql/mysql-regex-metacharacters.htm 更多示例: http//www.shayanderson.com/mysql/mysql-regex-metacharacters.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM