I'm attempting to build a query that finds companies that are within a proximity/distance from a zip code.
Right now a user enters a zip code (via web form) and a radius (1, 5, 10 miles, etc) and I'm using this PHP class to find the closest zip codes, radius, distance, etc (which is working great). Then I have a query that finds all companies which have these zip codes and lists them out.
The issue I have is that the zip codes are stored in three places in the database. They are either stored in the companies table, and/or one of two other related tables (simplified example below). And I can't figure out how to ORDER the results by the proximity regardless of where the zip code field is.
Tables:
company (table) id, name, zip
company_delivery (table) id, company_id (fk), zip
company_other_areas (table) id, company_id (fk), zip
$zip_codes is an array of zips outputted from the zip code class noted above where they are listed closest to furthest:
$zip_code_array = array(
90210,
90211,
90212
)
//* edited - thanks @crafter
$zip_codes = implode(', ', $zip_code_array);
The Query I'm working with
$sql="
SELECT
company.id, company.name, company.zip, company_delivery.zip, company_other_areas.zip
FROM
company
LEFT JOIN
company_delivery ON company.id = company_delivery.company_id
LEFT JOIN
company_other_areas ON company.id = company_other_areas.company_id
WHERE
company.zip IN($zip_codes) OR company_delivery.zip IN($zip_codes) OR company_other_areas.zip IN($zip_codes)
GROUP BY
company.id
ORDER BY
FIELD(company.zip, $zip_codes),
FIELD(company_delivery.postal_code, $zip_codes)
FIELD(company_other_areas.postal_code, $zip_codes)
";
I can't seem to figure out to order the companies by zip code, in the same order they are returned from the Zip Code class. - With the above query it orders by each "FIELD" independently. Is it possible to put all the returned zips codes from the database into a merged variable that can be ordered by?
Thanks for any help or pointers on this!