0

This question is self-answered to help people that need to create distance matrix in MySQL, which supports queries such as "select id2 from Distances where id1=10 and type1=0 and type2=1 and distance<10" which would find objects of type 1 in vicinity of 10 from object 10 of type 0.

The code assumes table structure similar to one described in Mysql Haversine distance calculation

If you ever find yourself in need of a distance matrix in mysql, here's a View definition for it:

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))

Where the geodistance_km_by_obj function is some distance calculation function, for example based on haversine calculation linked in the header.

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
Community
  • 1
  • 1
silvio
  • 899
  • 7
  • 5
  • In order to stick with the Q&A format, you should pose this as a question, and then answer your own question with the solution that you came up with. – Michael Fredrickson Apr 03 '12 at 22:44
  • Unfortunately, there is a delay of 8 hours between asking a question and answering it for low-rank users. Thanks for attention though. – silvio Apr 03 '12 at 23:17
  • It's been over 8 hours. If you edit this question and select your own answer as the correct one you can earn an extra badge (there is nothing wrong with sharing knowledge on this site) – Jason Sperske Jul 24 '12 at 18:42

0 Answers0