从DB中选择最近的经度/纬度值

时间:2012-06-03 16:59:40

标签: mysql sql

我有一个有几千个职位的数据库。这些是巴士站。我想做的是将X值最接近的值放到LON / LAT位置。

这是我桌子的布局:

CREATE TABLE IF NOT EXISTS `buss_StopPoints` (
  `Name` varchar(50) NOT NULL,
  `LocationNorthing` varchar(30) NOT NULL,
  `LocationEasting` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

这些是一些示例行:

INSERT INTO `buss_StopPoints` (`Name`, `LocationNorthing`, `LocationEasting`) VALUES ('Some station', '59.3195952318672', '18.0717401337168');
INSERT INTO `buss_StopPoints` (`Name`, `LocationNorthing`, `LocationEasting`) VALUES ('Some station 2', '59.3195772927918', '18.0717389396547');
INSERT INTO `buss_StopPoints` (`Name`, `LocationNorthing`, `LocationEasting`) VALUES ('Some station 3', '59.3234014331742', '18.0671617033088');
INSERT INTO `buss_StopPoints` (`Name`, `LocationNorthing`, `LocationEasting`) VALUES ('Some station 4', '59.3233921590479', '18.0671786573678');
INSERT INTO `buss_StopPoints` (`Name`, `LocationNorthing`, `LocationEasting`) VALUES ('Some station 5', '59.3313179695727', '18.061677395945');

我的问题:我如何制作一个select语句,从DB中选择最接近的X行数,无论是负方向还是正方向。 (例如,假设我要求59.3234014331742,18.0671617033088,并且想要最近的4个站点,这种情况应该全部返回)。

1 个答案:

答案 0 :(得分:2)

LAT = latitude value
LON = longitude value

SELECT Name, (6371 * acos( cos( radians(LAT) ) * cos( radians( LocationNorthing ) ) * cos( radians( LON ) - radians(LocationEasting) ) + sin( radians(LAT) ) * sin( radians(LocationNorthing) ) )) AS distance order by distance