What is the ideal data type to use when storing latitude / longitude in a MySQL database?

前端 未结 21 2903
梦如初夏
梦如初夏 2020-11-22 09:40

Bearing in mind that I\'ll be performing calculations on lat / long pairs, what datatype is best suited for use with a MySQL database?

21条回答
  •  再見小時候
    2020-11-22 10:22

    Depends on the precision that you require.

    Datatype           Bytes       resolution
    ------------------ -----  --------------------------------
    Deg*100 (SMALLINT)     4  1570 m    1.0 mi  Cities
    DECIMAL(4,2)/(5,2)     5  1570 m    1.0 mi  Cities
    SMALLINT scaled        4   682 m    0.4 mi  Cities
    Deg*10000 (MEDIUMINT)  6    16 m     52 ft  Houses/Businesses
    DECIMAL(6,4)/(7,4)     7    16 m     52 ft  Houses/Businesses
    MEDIUMINT scaled       6   2.7 m    8.8 ft
    FLOAT                  8   1.7 m    5.6 ft
    DECIMAL(8,6)/(9,6)     9    16cm    1/2 ft  Friends in a mall
    Deg*10000000 (INT)     8    16mm    5/8 in  Marbles
    DOUBLE                16   3.5nm     ...    Fleas on a dog
    

    From: http://mysql.rjweb.org/doc.php/latlng

    To summarise:

    • The most precise available option is DOUBLE.
    • The most common seen type used is DECIMAL(8,6)/(9,6).

    As of MySQL 5.7, consider using Spatial Data Types (SDT), specifically POINT for storing a single coordinate. Prior to 5.7, SDT does not support indexes (with exception of 5.6 when table type is MyISAM).

    Note:

    • When using POINT class, the order of the arguments for storing coordinates must be POINT(latitude, longitude).
    • There is a special syntax for creating a spatial index.
    • The biggest benefit of using SDT is that you have access to Spatial Analyses Functions, e.g. calculating distance between two points (ST_Distance) and determining whether one point is contained within another area (ST_Contains).

提交回复
热议问题