将行从一个表添加到另一个现有表,其中主键是自动生成的

时间:2014-02-19 06:15:42

标签: mysql sql pentaho

我有两个表格,表1(idname)和表2(idname)。

表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

3 个答案:

答案 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 )