SQL:插入...值...选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/856707/
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
SQL: INSERT INTO...VALUES..SELECT
提问by Andomar
How do i write INSERT statement if i get the values of colA from TableX, colB from TableY and colC from TableZ?
如果我从 TableX 中获取 colA、从 TableY 中获取 colB 和从 TableZ 中获取 colC 的值,我该如何编写 INSERT 语句?
eg: INSERT INTO TableA (colA, colB, colC) VALUES (?,?,?)
例如:INSERT INTO TableA (colA, colB, colC) VALUES (?,?,?)
Any ideas if it is possible?
如果可能,有什么想法吗?
回答by marc_s
INSERT INTO TableA(colA, colB, colC)
SELECT TableX.valA, TableY.valB, TableZ.valC
FROM TableX
INNER JOIN TableY ON :......
INNER JOIN TableZ ON ........
Of course, TableX, TableY and TAbleZ might also be related in some other way (not INNER JOIN).
当然,TableX、TableY 和 TAbleZ 也可能以其他方式相关(不是 INNER JOIN)。
If you cannot find any relation between the tables AT ALL, you could also do three separate
如果你根本找不到表之间的任何关系,你也可以做三个单独的
SELECT @value1 = valA FROM TableX WHERE ......
SELECT @value2 = valB FROM TableY WHERE ......
SELECT @value3 = valC FROM TableZ WHERE ......
and then an insert like this:
然后是这样的插入:
INSERT INTO TableA(colA, colB, colC)
VALUES(@value1, @value2, @value3)
That's the ultimate last resort, you can can't express everything in a single SELECT
statement.
这是最后的最后手段,你不能用一个SELECT
语句来表达所有的东西。
Marc
马克
回答by Andomar
In response to marc_s's answer, you can query from unrelated tables in a since select like:
为了响应 marc_s 的回答,您可以从 a since select 中的不相关表中进行查询,例如:
INSERT INTO TableA
(colA, colB, colC)
SELECT
(SELECT valA FROM TableX WHERE ...),
(SELECT valB FROM TableY WHERE ...),
(SELECT valC FROM TableZ WHERE ...)
回答by Binary Worrier
Insert into TableA (ColA, ColB, ColC) . . .
Must be the column names as the are in Table A. There's nothing wrong with
必须是表 A 中的列名。没有任何问题
Insert into TableA (ColA, ColB, ColC) . . .
Select TableX.Col1, TableY.Col1, TableZ.Col5
From TableX, TableY, TableZ
Where . . .
回答by lexx
You will need to join the tables that you want to make the selection from.
您需要连接要从中进行选择的表。
Here is a resource on SQL joins:
这是有关 SQL 连接的资源:
www.w3schools.com/sql/sql_join.asp
www.w3schools.com/sql/sql_join.asp
You also might want to check out this free PDF book from the guys at www.simple-talk.comthat covers SQL basics:
您可能还想从www.simple-talk.com上的人那里查看这本免费的 PDF 书,其中涵盖了 SQL 基础知识: