如何将两个以上的表组合成一个具有自动增量ID的新表?

时间:2018-04-24 16:56:29

标签: mysql database union

在我的数据库中,我有三个不同的表。我的表看起来很相似,但有不同的表名,如下面的结构:

Table_One
    +------+----+
    |id|JAN||FEB|
    +------+----+
    |1 |  1||  5|
    +------+----+
    |2 |  8|| 12|
    +------+----+
    |3 | 15|| 19|
    +------+----+
    |4 | 22|| 26|
    +------+----+

Table_Two
    +------+----+
    |id|JAN||FEB|
    +------+----+
    |1 |  1||  5|
    +------+----+
    |2 |  8|| 12|
    +------+----+
    |3 | 15|| 19|
    +------+----+
    |4 | 22|| 26|
    +------+----+

Table_Three
    +------+----+
    |id|JAN||FEB|
    +------+----+
    |1 |  1||  5|
    +------+----+
    |2 |  8|| 12|
    +------+----+
    |3 | 15|| 19|
    +------+----+
    |4 | 22|| 26|
    +------+----+

现在我想通过将所有三个表合并在一起来创建新表,这应该看起来像下面的结构。

Table_Final
        +------+----+
        |id |JAN|FEB|
        +------+----+
        |1  |  1|  5|
        +------+----+
        |2  |  8| 12|
        +------+----+
        |3  | 15| 19|
        +------+----+
        |4  | 22| 26|
        +------+----+
        |5  |  1|  5|
        +------+----+
        |6  |  8| 12|
        +------+----+
        |7  | 15| 19|
        +------+----+
        |8  | 22| 26|
        +------+----+
        |9  |  1|  5|
        +------+----+
        |10 |  8| 12|
        +------+----+
        |11 | 15| 19|
        +------+----+
        |12 | 22| 26|
        +------+----+

我通过UNION操作使用合并表多次尝试了几次。但问题是,在使用UNION操作创建新表后,新表没有创建auto_increment id,因此我没有获得任何更新的权限,删除新表中数据的选项。

2 个答案:

答案 0 :(得分:1)

使用MySQL的用户变量,这也可以不使用额外的表格 但是这个查询将始终确保相同的id,因为关闭了ORDER BY ..

SELECT
   (@id := @id + 1) AS id   
 , JAN
 , FEB
FROM (

  SELECT

     JAN
   , FEB

  FROM (
    SELECT
       id 
     , JAN
     , FEB
     , 1 AS position
    FROM
     Table_One  

    UNION ALL 

    SELECT 
       id 
     , JAN
     , FEB
     , 2 AS position
    FROM
     Table_Two

    UNION ALL 

    SELECT 
       id 
     , JAN
     , FEB
     , 3 AS position
    FROM
     Table_Three

  ) AS Tables
  CROSS JOIN ( SELECT @id := 0 ) AS init_user_param
  ORDER BY 
     position ASC
   , id ASC
) AS Tables_user_param

答案 1 :(得分:0)

您可以创建一个id为auto_increment

的表
  CREATE TABLE `table_final` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `jan` int(11) NOT NULL,
    `feb` int(11) NOT NULL,
    PRIMARY KEY (`id`),
  ) ;

然后使用选择联合填充

    insert into table_final ( jan, feb)
    select jan, feb 
    from Table_One
    union 
    select jan, feb 
    from Table_Two 
    union 
    select jan, feb 
    from TTable_Three