我有两个表格,表1(id
,name
)和表2(id
,name
)。
表1看起来像:
id name
1 ABC
2 DEF
表2看起来像:
id name
1 XYZ
2 ASD
有人可以说明如何将Table2行添加到Table1,即
Table1最终必须如下:
id name
1 ABC
2 DEF
3 XYZ
4 ASD
答案 0 :(得分:1)
Insert into table1 (name)
Select name from table2
答案 1 :(得分:0)
如下所示,如果id
中的table1
不是auto_increment
SELECT * FROM table1;
+------+------+
| id | name |
+------+------+
| 1 | ABC |
| 2 | DEF |
+------+------+
2 rows in set (0.00 sec)
SELECT * FROM table2;
+------+------+
| id | name |
+------+------+
| 1 | PQR |
| 2 | XYZ |
+------+------+
2 rows in set (0.00 sec)
SELECT MAX(id) INTO @row FROM table1;
Query OK, 1 row affected (0.00 sec)
INSERT INTO table1 SELECT @row := @row + 1 as row, name FROM table2;
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
SELECT * FROM table1;
+------+------+
| id | name |
+------+------+
| 1 | ABC |
| 2 | DEF |
| 3 | PQR |
| 4 | XYZ |
+------+------+
4 rows in set (0.00 sec)
答案 2 :(得分:0)
消除重复:
INSERT INTO table1 (name)
SELECT name
FROM table2 t2
WHERE NOT EXISTS(SELECT * FROM table1 t1 WHERE t1.name = t2.name )