I'm building a website with PHP and MYSQL.
I'm trying to order my search results by nearest location first. I have a items table and a deals table. I need to search BOTH of these tables for the item/deal location and then compare the location to my postcode database and get the latitude and longitude from the corresponding database entry and sort the results. I'm using PDO prepared statements.
I have 3 tables in my Database. Postcodes, Deals and Items.
POSTCODES
| postcode | lat | lng |
DEALS
| id | title | location |
ITEMS
| id | title | location |
Here's my SQL...
SELECT SQL_CALC_FOUND_ROWS *
FROM (
SELECT *
FROM items
UNION
SELECT * FROM deals
) AS allitemsdeals
INNER JOIN (
SELECT
postcodes.*,
(3959 * acos(cos(radians(custom.lat)) * cos(radians(postcodes.lat)) * cos(radians(custom.lng) - radians(postcodes.lng)) + sin(radians(custom.lat)) * sin(radians(postcodes.lat)))
) AS distance
FROM postcodes
INNER JOIN postcodes AS custom
WHERE custom.postcode = ?
) postcodes ON allitemsdeals.location = postcodes.postcode
HAVING distance < 5 ORDER BY id LIMIT ? OFFSET ?
I'm having a problem with my the join on this. The query works but it takes about a minute! :(
Any help would be greatly appreciated! Thanks! :)