0

这个问题是自我回答的,以帮助需要在 MySQL 中创建距离矩阵的人,它支持诸如“从距离中选择 id2,其中 id1=10 和 type1=0 和 type2=1 和距离<10”这样的查询,可以找到对象类型 1 在类型 0 的对象 10 的 10 附近。

代码假定表结构类似于Mysql Haversine distance 计算中描述的表结构

如果您发现自己需要 mysql 中的距离矩阵,这里是它的视图定义:

select o1.object_id AS id1,o1.object_type AS type1,o2.object_id AS id2,o2.object_type AS type2,geodistance_km_by_obj(o1.object_id,o1.object_type,o2.object_id,o2.object_type) AS distance from (Coordinates o1 join Coordinates o2) where ((o1.object_id,o1.object_type) <> (o2.object_id,o2.object_type))

其中geodistance_km_by_obj函数是一些距离计算函数,例如基于标题中链接的半正弦计算。

CREATE FUNCTION geodistance_km_by_obj(object_id1 INT, object_type1 TINYINT, object_id2 INT, object_type2 TINYINT)
RETURNS float
LANGUAGE SQL
DETERMINISTIC
READS SQL DATA
SQL SECURITY INVOKER
COMMENT 'returns distance in km'
BEGIN
declare sl1 float;
declare cc1 float;
declare cs1 float;
declare sl2 float;
declare cc2 float;
declare cs2 float;

select sin_lat,cos_cos,cos_sin into sl1, cc1, cs1 from Coordinates where object_id=object_id1 and object_type=object_type1;
select sin_lat,cos_cos,cos_sin into sl2, cc2, cs2 from Coordinates where object_id=object_id2 and object_type=object_type2;
return cast(round(acos(sl1*sl2 + cc1*cc2 + cs1*cs2)*6371,0) as decimal);
END
4

0 回答 0