【问题标题】:How to copy one table into another with some additional Data如何使用一些额外的数据将一个表复制到另一个表中
【发布时间】:2020-02-13 08:22:18
【问题描述】:

我想将 table1 中的列复制到 table2 中,并在 table2 中添加一些列。

虽然我知道语法:

INSERT INTO table2
SELECT * FROM table1
WHERE condition;

但是如何在 table2 中添加额外的列数据?

我已经尝试过这种方法,但它给出了语法错误:

// first storing the desired data from table1 into a temporary table
CREATE TEMPORARY TABLE temp_table 
select column1, column2, column3 from table1 
where condition;

// then placing the selected columns into table2
INSERT INTO table2 (col1, col2, col3,col4) values (
SELECT column1 FROM temp_table, 
SELECT column2 FROM temp_table, 
SELECT column3 FROM temp_table, 
'Additional Value'
);

【问题讨论】:

    标签: mysql sql database sql-insert


    【解决方案1】:

    您可以将文字字符串(或任何其他表达式)添加到列列表中。考虑:

    INSERT INTO table2 (col1, col2, col3,col4)
    SELECT
        column1,
        column2,
        column3,
        'Additional Value'
    FROM table1
    

    【讨论】:

    • 它不必是“文字字符串”。代替'Additional value',您还可以输入一个数字,即:42,或计算2*3*7
    • @Luuk:当然。我编辑了我的答案以更准确地说明这一点。
    【解决方案2】:

    请按照下面的查询,您可以使用别名作为额外的列 静态或表达式字段: (SQL-Fiddle)

    INSERT INTO table2 (col1, col2, col3, col4)
     SELECT column1, column2, column3, 'Additional Value' as column4
     FROM table1
     WHERE condition;
    

    【讨论】:

    • 谢谢兄弟,它也可以,但在这种情况下不需要设置别名
    猜你喜欢
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多