I currently have this query:
SELECT *, GEODIST(41.3919671, 2.1757278, latitude, longitude) distance
FROM offers_all
WHERE id_family=1761 AND GEODIST(41.3919671, 2.1757278, latitude, longitude) <= 40
GROUP BY id_prod ORDER BY pricepromo ASC
As you can see, it uses a MySQL procedure, called GEODIST (Haversine formula, returns distance in KM between the coords), and groups results by id_prod
.
The table may contain more than one offer per product (id_prod
). The objective is to retrieve the offer list, with no duplicate products, therefore returning the best (cheapest, closest) case for that offer.
The previous query seems to do the job well, but for further optimization I'd like to use HAVING
(not having to run Haversine's twice for each row). This was my first thought:
SELECT *, MIN(GEODIST(41.3919671, 2.1757278, latitude, longitude)) distance
FROM offers_all
WHERE id_family=1761
GROUP BY id_prod
HAVING distance <= 40
ORDER BY pricepromo ASC
Sadly, this query does not return the same results as previously.
Without using the MIN()
, the results were incorrect (returns just one row). Using MIN()
(as in that last query), row information is incorrect (ie. not returning the row that was expected, leading to results showing in the listing the wrong shop name and price).
Any tips or answers about the best query for this objective (and other proposals) are welcome :D