Postcode search sql problem

Hi Guys!

I’ve developed a postcode search that is used to find candidates in our database. Now, a user can have multiple postcodes associated with them (stored in the users_locations) table. My problem is that when we search for a postcode sometimes the user doesn’t come up even though they exist with that postcode associated with them.

For example, a user may have the following 3 postcodes associated with them:

CM5
CM6
CM14

When I search for CM5 and CM6 the user is found. However if I search for CM14 it doesn’t get found. Does anyone have an idea why? Is it a GROUP BY problem maybe?

Here is the SQL


SELECT users . * , l.display_name, l.postcode, l.display_county
FROM users
INNER JOIN (

SELECT user_id, if( count( user_id ) >3, 'Locations throughout the UK', group_concat( display_name
SEPARATOR ' ' ) ) AS display_name, postcode, display_county, location_id
FROM users_locations
GROUP BY user_id
) AS l ON l.user_id = users.id
WHERE users.status = '1'
AND users.cv_hide = '0'
ORDER BY cv_date DESC
LIMIT 0 , 30

looks like a user can have multiple rows in the users_locations table, but you are collapsing them all down to one aggregate row per user_id

if you do a GROUP_CONCAT on the display_name, then you should also do that on the other columns in the SELECT clause

i’ll bet you find CM14 appearing, as if by magic…

Hi,

So you mean like this?


SELECT users. * , l.display_name, l.postcode, l.display_county
FROM users
INNER JOIN (
SELECT user_id, if( count( user_id ) >3, 'Locations throughout the UK', group_concat( display_name
SEPARATOR ' ' ) ) AS display_name, group_concat( postcode
SEPARATOR ' ' ) AS postcode, display_county, location_id
FROM users_locations
GROUP BY user_id
LIMIT 0 , 30

I just ran the above code but it gave a syntax error. :frowning:

I think I managed to figure it out. Here’s the final SQL:

SELECT users . * , l.display_name, l.postcode, l.display_county
FROM users
INNER JOIN (

SELECT user_id, if( count( user_id ) >3, 'Locations throughout the UK', group_concat( display_name
SEPARATOR ' ' ) ) AS display_name, group_concat( postcode
SEPARATOR ' ' ) AS postcode, display_county, location_id
FROM users_locations
GROUP BY user_id
) AS l ON l.user_id = users.id
WHERE users.status = '1'
AND users.cv_hide = '0'
AND (
l.postcode LIKE '%CM14%'
)
ORDER BY cv_date DESC
LIMIT 0 , 30 

oh

and you’re happy with it?