[英]How do I INSERT INTO from one mysql table into another table and set the value of one column?
[英]How can I insert one table as value to another one in mysql?
我有这两个表,第一个表称为item_coordinates,类型为INT,DOUBLE,DOUBLE
itemID | latitude | longitude
-------------+-----------+-----------
1679323860 | 36.531398 | -82.98085
1679340420 | 29.178171 | -74.075391
1679386982 | 40.73235 | -94.6884
现在,我有了另一个名为Geocoordinates的表,该表的创建过程如下:
CREATE TABLE Geocoordinates (ItemID INT PRIMARY KEY,
Geo_Coordinates POINT) ENGINE = MyISAM;
现在,我想将表1中的值插入表2中,但仍会收到错误消息。 这是我的尝试:
INSERT INTO Geocoordinates (ItemID, Geo_Coordinates) VALUES (item_id,
POINT(latitude, longitude)) SELECT item_id, latitude, longitude FROM
item_coordinates);
提前致谢。
我认为您需要使用CONCAT函数将经纬度分组为一个字段
INSERT INTO Geocoordinates (ItemID, Geo_Coordinates) VALUES (item_id,
POINT(latitude, longitude)) SELECT item_id, CONCAT(latitude, longitude) FROM item_coordinates);
我认为在这种情况下不需要POINT。
使用INSERT INTO SELECT,不应指定VALUES关键字。 以下是完整的演示。
SQL:
-- Data
create table item_coordinates( itemID bigint, latitude decimal(10,6), longitude decimal(10,6));
CREATE TABLE Geocoordinates (ItemID INT PRIMARY KEY,
Geo_Coordinates POINT) ENGINE = MyISAM;
INSERT INTO item_coordinates values
(1679323860 , 36.531398 , -82.98085),
(1679340420 , 29.178171 , -74.075391),
(1679386982 , 40.73235 , -94.6884);
SELECT * FROM item_coordinates;
-- SQL needed
INSERT INTO Geocoordinates (itemID, Geo_Coordinates) SELECT itemID, POINT(latitude, longitude) FROM item_coordinates;
SELECT itemID, ST_AsText(Geo_Coordinates) FROM Geocoordinates;
输出:
mysql> SELECT * FROM item_coordinates;
+------------+-----------+------------+
| itemID | latitude | longitude |
+------------+-----------+------------+
| 1679323860 | 36.531398 | -82.980850 |
| 1679340420 | 29.178171 | -74.075391 |
| 1679386982 | 40.732350 | -94.688400 |
+------------+-----------+------------+
3 rows in set (0.00 sec)
mysql> INSERT INTO Geocoordinates (itemID, Geo_Coordinates) SELECT itemID, POINT(latitude, longitude) FROM item_coordinates;
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT itemID, ST_AsText(Geo_Coordinates) FROM Geocoordinates;
+------------+-----------------------------+
| itemID | ST_AsText(Geo_Coordinates) |
+------------+-----------------------------+
| 1679323860 | POINT(36.531398 -82.98085) |
| 1679340420 | POINT(29.178171 -74.075391) |
| 1679386982 | POINT(40.73235 -94.6884) |
+------------+-----------------------------+
3 rows in set (0.00 sec)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.