Question

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

Was it helpful?

Solution

You can do this with a derived table:

SELECT t.*, MIN(t.distance) AS distance
FROM (SELECT *, GEODIST(41.3919671, 2.1757278, latitude, longitude) AS distance
    FROM offers_all
    WHERE id_family=1761) AS t
WHERE t.distance <= 40
GROUP BY t.id_prod
ORDER BY t.pricepromo ASC

OTHER TIPS

I'm pretty sure some people will suggest the same-table-alias-join approach, so i'll take the "other proposals" attempt:

Are you already using Sphinx in that project, maybe for fulltext product searching ? Sphinx can give you built-in support for geodistances, just some random URLs i got in the past on the subject:

http://www.fliquidstudios.com/2011/06/17/an-introduction-to-distance-based-searching-in-sphinx/

http://www.sanisoft.com/blog/2011/05/02/geo-distance-search-in-sphinx/

More on the subject in the Sphinx forum itself:

http://sphinxsearch.com/forum/view.html?id=7276

In addition, maybe you would prefer to take the "Tiles" approach for perfomance:

http://sphinxsearch.com/forum/view.html?id=7823

http://sphinxsearch.com/forum/view.html?id=2482

http://sphinxsearch.com/forum/view.html?id=5688

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top