这个问题是自我回答,以帮助需要在MySQL中创建距离矩阵的人,它支持诸如“从距离中选择id2 = id1 = 10且type1 = 0且type2 = 1且距离<10”的查询从类型0的对象10中找到类型1的对象在10附近。
该代码假设表结构类似于Mysql Haversine distance calculation
中描述的表结构如果你发现自己需要mysql中的距离矩阵,这里有一个View定义:
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