簡體   English   中英

如何在MySQL中將一個表作為值插入另一個表?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM