MySQL 从一张表中选择并插入到另一张表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2377547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:26:34  来源:igfitidea点击:

select from one table and insert into another

sqlmysql

提问by nrk

I've got two tables.

我有两张桌子。

Table_A (nid, vid, type, title, uid)

Table_B (id, questiontext)

表_A(nid、vid、类型、标题、uid)

Table_B (id, questiontext)

I need to insert records from Table_B into Table_A. I tried this:

我需要将 Table_B 中的记录插入到 Table_A 中。我试过这个:

INSERT INTO Table_A (nid, vid, type, title, uid)
VALUES ('', '', multichoice', (SELECT questiontext from Table_B), '1')

but it's throwing an error.

但它抛出了一个错误。

What should be the correct statement?

正确的说法应该是什么?

UPD: I should add that nid is autoincrement and the value of vid should be same as nid.

UPD:我应该补充一点,nid 是自动递增的,vid 的值应该与 nid 相同。

回答by Adriaan Stander

Have you tried

你有没有尝试过

INSERT INTO Table_A (nid, vid, type, title, uid) 
SELECT  '', 
        '', 
        'multichoice', 
        questiontext ,
        '1'
from    Table_B

Have a look at INSERT ... SELECT Syntax

看看INSERT ... SELECT 语法

回答by Matthias Meid

You should use the following SQL query:

您应该使用以下 SQL 查询:

INSERT INTO Target(A, B, C)
  SELECT A, B, C
    FROM Source

回答by Dan Beam

According to the the MySQL reference for INSERT SELECT:

根据INSERT SELECT的 MySQL参考

INSERT INTO table_name SELECT FROM other_table [ WHERE ... something ... ]

回答by Pavunkumar

use this method

使用这个方法

INSERT INTO destination (column names ) (select columnaes from example 3 );

Column should be same type here .

INSERT INTO 目标(列名)(从示例 3 中选择列);

这里的列应该是相同的类型。

回答by Digpal Singh

insert into table2(columnname)select columnname from table1

回答by Basil Mohammed

INSERT INTO Table_1 (column_1, column_2, column_3)
SELECT column_1, column_2, column_3
FROM Table_2
INSERT INTO Table_1 (column_1, column_2, column_3)
SELECT column_1, column_2, column_3
FROM Table_2

You can also set some conditions for inserting by as follows:

您还可以通过如下方式设置一些插入条件:

INSERT INTO Table_1 (column_1, column_2, column_3)
SELECT column_1, column_2, column_3
FROM Table_2
WHERE (Condition)
INSERT INTO Table_1 (column_1, column_2, column_3)
SELECT column_1, column_2, column_3
FROM Table_2
WHERE (Condition)

回答by Local

I think the correct answer to this might be select into, from what I see from the other answers is that you guys insert before getting the value from table B as you should first get the value that is : SELECT from table B then insert into table A. you should be searching on the lines of select into

我认为对此的正确答案可能是 select into,从我从其他答案中看到的是,你们在从表 B 获取值之前插入,因为您应该首先获取值:从表 B 中选择然后插入到表中A. 你应该在 select into 的行上搜索