1

I have two mysql tables:

table 1:

    id  name  type
     1    a    123
     2    b    125

table 2:

    id  text
    1   test1
    2   test2

these two tables need to be merged into a third table

table3:

    id name type text

The id is an auto increment id. the first two tables have data that are not related. I mean, row for id=1 in table 1 has nothing to do with the row for id=1 in table two. So, I basically want to write a sql script which would insert values into table 3 to look like this in the end:

table3:

    id name  type   text
    1   a    123
    2   b    125
    3               test1
    4               test2

the ids in the old tables and the new table don't have to match. Just the data from the tables need to be in the new table. I am very new to mysql and if anyone can help me with this, it would be great!

thanks!

4

2 回答 2

5

可以通过以下方式完成:

CREATE TABLE Table3 (
  id int auto_increment, 
  name ..., 
  type int, 
  text ...,
  PRIMARY KEY (id)
);

INSERT INTO table3 (name, type, text) 
     SELECT name, type, text FROM (
       SELECT name, type, NULL AS text FROM table1
       UNION ALL
       SELECT NULL as name, NULL as type, text FROM table2) AS t

使用自动增量,我们根本不需要重新计算id

这是一个供您使用的SQL Fiddle 。)

我实际上不明白你的方案中的空白空间是什么,并假设它都是 NULL。如果没有,您可以NULL在此查询中替换为您想要的任何默认值。

于 2012-09-19T17:06:30.710 回答
3

由于没有任何关系,从@raina77ow 的表开始,但只需使用两个查询:

INSERT INTO table3 (name, type, text)
SELECT name, type, NULL
from table1;

INSERT INTO table3 (name, type, text)
SELECT NULL, NULL, text
from table2;
于 2012-09-19T17:42:18.293 回答