Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL 'LIKE' query with spaces

Tags:

sql

mysql

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). Simlarly in the PHP query to read from the database the person searching the database may add a space or not. 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).

Any suggestions?

like image 275
Elliot Reed Avatar asked Aug 30 '13 08:08

Elliot Reed


2 Answers

I wouldn't even bother with LIKE or regex and simply remove spaces and compare the strings:

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.

like image 51
Aleks G Avatar answered Oct 05 '22 15:10

Aleks G


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

Make sure your PHP input is trimmed as well

like image 32
Anonymoose Avatar answered Oct 05 '22 14:10

Anonymoose