A custom MySQL function to calculate the Haversine distance?

后端 未结 1 1704
南旧
南旧 2020-12-22 00:35

I\'m building a \'find my nearest\' script whereby my client has provided me with a list of their locations. After some research, I determined that the way to do this was t

相关标签:
1条回答
  • 2020-12-22 01:21

    Yes, you can create a stored function for this purpose. Something like this:

    DELIMITER //
      DROP FUNCTION IF EXISTS Haversine //
      CREATE FUNCTION Haversine
        ( myLat FLOAT
        , myLong FLOAT
        , db_lat FLOAT
        , db_long FLOAT
        , unit VARCHAR(20)
        )
        RETURNS FLOAT
          DETERMINISTIC
        BEGIN
          DECLARE haver FLOAT ;
    
          IF unit = 'MILES'                    --- calculations
            SET haver = ...                --- calculations
    
          RETURN haver ;
        END  //
    DELIMITER ;
    

    I don't think it offers any speed gains but it's good for all the other reasons you mention: Readability, reusability, ease of maintenance (imagine you find an error after 2 years and you have to edit the code in a (few) hundred places).

    0 讨论(0)
提交回复
热议问题