Moving lat/lon text columns into a 'point' type column

◇◆丶佛笑我妖孽 提交于 2019-11-28 21:15:06

问题


I've got a table in my MySQL database called house.

Within the house table, there are a couple of text columns called latitude and longitude.

I've added a new column called coords, of type point - http://dev.mysql.com/doc/refman/5.0/en/gis-class-point.html

How would I move the latitude and longitude values into the new coords column?


回答1:


Assuming you want a SPATIAL index on this column:

ALTER TABLE mytable ADD coords Point;

UPDATE  mytable
SET     coords = Point(lon, lat);

ALTER TABLE mytable MODIFY coords POINT NOT NULL;

CREATE SPATIAL INDEX sx_mytable_coords ON mytable(coords);

If you don't, you can omit the last two steps.

Update:

In earlier versions of MySQL, you would need to populate Point columns using WKT:

UPDATE  mytable
SET     coords = GeomFromText(CONCAT('POINT (', lon, ' ', lat, ')'))



回答2:


MySQL Version 5.5.8

My latitude and longitude are of type float. To update existing rows...

UPDATE table_name SET coord = POINT(longitude_field, latitude_field);

Something to consider, if you are collecting data and need to save the latitude and longitude separately, in their respective columns, I suggest adding a trigger to your table

CREATE DEFINER=`username`@`localhost` TRIGGER `table_name`.`create_point_geom` 
BEFORE INSERT ON database_name.table_name FOR EACH ROW
BEGIN
    SET NEW.coord = POINT(NEW.longitude, NEW.latitude);
END;

I collect geo-tagged social media data and I use this method to add geometry to my tables.




回答3:


Concisely:

UPDATE myTable SET coords = GeometryFromText( CONCAT( 'POINT(', lon, ' ', lat, ')' ) );

Note that answer from Quassnoi is in error since the proper input format is POINT(X Y), or in terms of earth POINT(lon lat).

Note you can show points via the X() and Y() functions like the following example:

SELECT X( GeometryFromText( CONCAT( 'POINT(', 35, ' ', 60, ')' ) ) ) AS x, Y( GeometryFromText( CONCAT( 'POINT(', 35, ' ', 60, ')' ) ) ) AS y;



回答4:


FINALLY! I was able to fix these errors:

#3037 - Invalid GIS data provided to function st_geometryfromtext.
#1416 - Cannot get geometry object from data you send to the GEOMETRY field

By doing a custom SQL query, where I pointed the lat and long points. In my case, the SQL string that did it was:

UPDATE wp_wpgmza SET latlng = GeometryFromText( CONCAT( 'POINT(', 38.5775167, ' ', -121.4868583, ')' ) ) WHERE id = 63;


来源:https://stackoverflow.com/questions/5756232/moving-lat-lon-text-columns-into-a-point-type-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!