【问题标题】:Select identicle columns from two tables while insertion in MySQL在 MySQL 中插入时从两个表中选择相同的列
【发布时间】:2013-03-01 09:24:07
【问题描述】:

我在不同的数据库上有两个相同的表

Database : live
table : customer
id | name | email | address

Database : test
table : customer
id | name | email | address | phone | post_code | company

这只是示例结构。我在实时数据库表中有 15 个字段,在测试数据库表中有 35 个字段。我想编写一个查询,它可以将数据从实时插入到测试数据库表中。我怎样才能做到这一点。这个我试过了

INSERT INTO test.customer
SELECT *
FROM live.customer as cd
WHERE NOT EXISTS(SELECT * from test.customer);

如果它们的顺序不同,这会将数据插入错误的列中。
这是我尝试过的另一种方式

INSERT INTO test.customer (id,name,email,address)
SELECT *
FROM live.customer as cd
WHERE NOT EXISTS(SELECT * from test.customer);

这很好,但我不想写 15 个列名。如何从实时数据库表中选择所有列并将其结果放入插入的 () 中。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    我认为没有纯 SQL 解决方案。但您可以使用动态查询,以这种方式创建:

    SET @sql = null;
    
    SELECT
      CONCAT('INSERT INTO test.customer (',
        group_concat(CONCAT('`', COLUMN_NAME, '`') separator ','),
        ') SELECT ',
        group_concat(CONCAT('`', COLUMN_NAME, '`') separator ','),
        ' FROM live.customer WHERE NOT EXISTS(SELECT * from test.customer)')
    FROM `INFORMATION_SCHEMA`.`COLUMNS` 
    WHERE `TABLE_NAME`='customer' AND `TABLE_SCHEMA`='test'
    INTO @sql;
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    SELECT * FROM test_customer;
    

    请看小提琴here

    【讨论】:

    • @raheelshan 我更新了我的答案,因为不能保证使用 GROUP_CONCAT 列名总是以相同的顺序返回,最好在 SELECT 部分也指定列名而不是使用 *,我还添加了一个 CONCAT 来引用列名,希望这会有所帮助:)
    猜你喜欢
    • 2018-05-11
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    相关资源
    最近更新 更多