开发者

Mysql Recursive Query / Spherical Law of Cosines

开发者 https://www.devze.com 2023-02-02 02:34 出处:网络
I want to search nearest locations from coordinates (lat/lng) into mysql database, I use spherical law of cosines to searching these places :

I want to search nearest locations from coordinates (lat/lng) into mysql database, I use spherical law of cosines to searching these places :

SELECT onlycoord.id, locations.name, locations.ascii,
    locations.latitude, locations.longitude,
    locations.country, locations.elevation,
    locations.gtopo30, locations.timezone,
    (6371 * ACOS(
        COS( RADIANS( 48.48 ) ) *
        COS( RADIANS( onlycoord.latitude ) ) *
        COS(
            RADIANS( onlycoord.longitude ) -
            RADIANS( 2.20 )
        ) +
        SIN( RADIANS( 48.48 ) ) *
        SIN( RADIANS( onlycoord.latitude ) )
    )) AS distance
FROM onlycoord USE INDEX (coordinate)
    LEFT JOIN locations USE INDEX (id)
    ON (onlycoord.id = locations.id)
WHERE onlycoord.latitude BETWEEN (
    48.48 - ( 5 / 111 )
) AND (
    48.48 + ( 5 / 111 )
) AND onlycoord.longitude BETWEEN (
    2.20 - ( 5 / ABS( COS(
        RADIANS( 48.48 )
    ) * 111 ) )
) AND (
    2.20 + ( 5 / ABS( COS(
        RADIANS( 48.48 ) 
    ) * 111 ) )
)
ORDER BY distance ASC
LIMIT 0, 20

Where 6371 is earth radius (km), 111 (km) is 1° of latitude, cos(latitude) * 111 (km) is 1° of longit开发者_StackOverflow社区ude and 5 (km) is search radius.

Problem : I want a minimum of 8 cities found, but 5 kms radius is small but fast for condensed zone (many cities), so if I use a search radius too big for condensed zone, query is slow (many results : order by), but for non-condensed the search radius is too small to find at least 8 cities...

How can I make a recursive query which increases automatically the search radius (x2) if the count of found cities < 8 (using mysql only) ?

Thanks


MySQL doesn't support recursive queries.

You have to make new queries depending on the result of the previous query.

By the way, for spatial queries I'd recommend a spatial database.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号