【问题标题】:Find closest longitude and latitude in a database? [duplicate]在数据库中查找最近的经度和纬度? [复制]
【发布时间】:2021-01-05 20:05:15
【问题描述】:

我正在尝试构建一个报价系统,根据与配送中心的距离进行报价。

我有一张表(table1),其中包含该国所有邮政编码及其对应的经纬度

我有另一个表 (table2),其中包含我所有的运输中心及其邮政编码和对应的经纬度。

因此,当用户输入他们的邮政编码时,我可以使用以下代码从我的数据库中获取他们的经纬度:

$pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $pdo->prepare("SELECT name, lng, lat FROM posts WHERE code=:code");
$stmt->execute(['code' => $post1]); 

while ($row = $stmt->fetch()) {
    $lng1 = $row['lng'];
    $lat1 =  $row['lat'];
    $name1 =  $row['name'];
}

echo "name 1: ".$name1;
echo "<br>";
echo "post code 1: ".$lng1;
echo "<br>";
echo "post code 1: ".$lat1;

我如何使用那个 long 和 lat 来找到表 2 中最近的枢纽?

【问题讨论】:

  • 我只想在重复的 qurstion 中再添加一个想法:如果您已经知道所有送货地址坐标和所有中心坐标,那么您可以预先计算所有可能的距离并将其存储在表格中。中心和邮政编码坐标很少更改,在这种情况下,您可以刷新您的表格。

标签: php mysql sql subquery spatial


【解决方案1】:

MySQL 有spatial support;您可以从坐标使用 build points,然后使用 st_distance_sphere() 计算距离:

select *
from (
    select p.name post_name, p.lng post_lng, p.lat post_lat, 
        h.name, hub_name, h.lng hub_lng, h.lat hub_lat,
        row_number() over(
            order by st_distance_sphere(point(p.lng, p.lat), point(h.lng, h.lat))
        ) rn
    from posts p
    cross join hubs h 
    where code =: code
) t
where rn = 1

您也可以使用子查询来做到这一点:

select p.name post_name, p.lng post_lng, p.lat post_lat, 
    h.name, hub_name, h.lng hub_lng, h.lat hub_lat
from posts p
inner join hubs h on h.id = (
    select id
    from hubs h1
    order by st_distance_sphere(point(p.lng, p.lat), point(h1.lng, h1.lat))
    limit 1
)

【讨论】:

    猜你喜欢
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 2016-11-22
    相关资源
    最近更新 更多