如何将两个以上的表合并成一个具有自动递增id的新表?

zc0qhyus  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(363)

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

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操作创建新表之后,新表不会创建自动增量id,因此,我在新表的数据中没有任何更新、删除选项的权限。

2wnc66cl

2wnc66cl1#

您可以创建一个id为auto\u 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
s1ag04yj

s1ag04yj2#

使用mysql的用户变量,也可以不使用额外的表
但此查询将始终确保相同的id,因为off the 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

相关问题