MySQL calculates the nearest store

Source: Internet
Author: User
Tags cos pow sin

Incoming parameters latitude 40.0497810000 longitude 116.3424590000/*The parameter passed in is latitude latitude longitude asc ascending from near to far desc descending from far to near*/SELECT*,ROUND(        6378.138 * 2 *ASIN(            SQRT(                POW(                    SIN(                        (                            40.0497810000 *PI()/180-lat *PI()/180                        ) /2                    ), 2                ) +COS(40.0497810000 *PI()/180) *COS(LAT *PI()/180) *POW(                    SIN(                        (                            116.3424590000 *PI()/180-lon *PI()/180                        ) /2                    ), 2                )            )        ) * 1000    )  asJulifrom CustomerOrder by Juli ASC

This will calculate all the stores in the database once, and in the actual use, it is unlikely that the need to calculate the user's distance from all other users, and then sort the situation, when the number of users reached a level, you can search in a smaller scope, rather than all users.

So for this example, I've added 4 where conditions, only for distance calculations for users with longitude and latitude greater than or less than 1 degrees (111 km) of the user, and an index to the longitude and latitude two columns in the data table to optimize the speed at which the where statement executes.

The final SQL statement is as follows

$sql=SELECT * from users_location where latitude >‘.$lat.‘-1 and Latitude <‘.$lat.‘+1 and Longitude >‘.$lon.‘-1 and longitude <‘.$lon.‘+1 ORDER by ACOS (SIN (‘.$lat. ' * 3.1415)/*sin ((Latitude * 3.1415)/+cos ('.$lat) * COS ((latitude * 3.1415)/3.1415) *cos (('.$lon.‘ * 3.1415)/Longitude-(* 3.1415)/+) * 6380 ASC limit 10 '; 

MySQL calculates the nearest store

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.