views:

38

answers:

1

I have a table that contains a list of the starting letters in a post code e.g. LS for Leeds and SO for Southampton.

I want to match these against a user entered full postcode e.g. LS19 1AB.

I've looked into using LIKE and some regexp stuff in my query but I'm struggling to find a way to do this the right way round.

Any ideas?

+1  A: 

You can turn the where clause around, and do some string manipulation tricks:

create table post_codes(
  post_code varchar(32)
);


mysql> insert into post_codes values("AS");
Query OK, 1 row affected (0.00 sec)

mysql> insert into post_codes values("LS");
Query OK, 1 row affected (0.00 sec)

mysql> select post_code from post_codes where 'LS19 1AB' like CONCAT(post_code,'%');
+-----------+
| post_code |
+-----------+
| LS        |
+-----------+
1 row in set (0.00 sec)
nos
ahh - wonderful, however if I have another row with value 'L' it will also return this, any way to match the first letter or two letters before the numbers
Chris Marshall
Sounds a bit harder, if you want the longest match, and only one match, you could add a `order by post_code desc limit 1;` though, on the other hand, if you know beforehand to only match 1 or 2 characters, you'd just do ` where SUBSTRING('LS19 1AB',1,2) = post_code;` when matching 2 letters.
nos