Ross
Ross

Reputation: 17967

Comparing values in MySQL table based on another tables rows

I am working on an application system in CakePHP. Each application contains the address and a (UK only) postcode of the applicant.

The client wants to be able to assign "postcode areas" to a given member of their team. Unfortunately the postcode area varies in format and length - examples: TA, TQ1, S60, BS22, TA6 4EJ

The user wants to be able to specify entire areas, or more specific areas on a per user basis if required. schema

I need to be able to take each prefix and compare it to the postcode for each application, and return any matches.


User Ross manages applications with postcode beginning with: BQ. BS and S60

User Dave manages applications with full postcodes: BS22 4JL and TA6 7EJ


I figured that the best way would be to have a table full of user-defined postcode prefixes:

   id  |  prefix
    1  |      TQ
    2  |      TL
    3  |     S50
    4  |     S55
    5  | TA6 4EJ

Each user is assigned a postcode area to manage.

I'm thinking if I can compare each application postcode to each prefix, I can retrieve all applications in a given postcode area, then look up the user that this belongs.

id | postcode
1  |  tq33 abc
2  |  TL5  8HA
3  |  s50 11l

The postcode data isn't in any standard/regular format unfortunately; so this might get tricky. It sounds like I need to JOIN the prefix on to the postcode; but as there's no key I don't think that's possible.

There's no direct association between prefix and postcode. Feel like I'm missing something fundamental

Any pointers?

Upvotes: 0

Views: 602

Answers (1)

yoprogramo
yoprogramo

Reputation: 1306

try:

SELECT users.name, app.* from applications app, users, postcodes where app.postcode LIKE CONCAT(postcodes.prefix,'%') AND postcodes.user_id = users.id

Upvotes: 1

Related Questions