MySQL INSERT INTO 来自多个表的表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13244489/
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
INSERT INTO Table from multiple tables
提问by ThingWings
Hey so I have a Junction table linking two unrelated tables. Both the tables have ID
's. I need to select the ID
from each table using WHERE
with different values, for example this is how I see it:
嘿,所以我有一个连接两个不相关表的连接表。两个表都有ID
's。我需要ID
使用WHERE
不同的值从每个表中选择,例如我是这样看的:
INSERT INTO c (aID, bID)
VALUES (SELECT a.ID WHERE a.Name="Me", SELECT b.ID WHERE b.Class="Math");
All the examples I've seen use a join
statement but the two tables have a common value, in this case they don't.
我见过的所有例子都使用了一个join
语句,但是这两个表有一个共同的值,在这种情况下它们没有。
回答by Yogendra Singh
Try this query:
试试这个查询:
INSERT INTO C (aID, bID)
SELECT A.ID, B.ID
FROM A, B
WHERE A.Name='Me'
AND B.Class='Math';
回答by Rohit Dubey
Another way can be
另一种方式可以是
INSERT INTO c (aID, bID)
SELECT
(SELECT A.id FROM TableA A WHERE A.names = 'sometext'),
B.id FROM TableB B
WHERE
B.x_name ='othertext';
回答by Nick
Assuming there is only one value in each table for the given Name
and Class
, the easiest method is just to enclose your subqueries in ()
:
假设每个表中给定的Name
and只有一个值Class
,最简单的方法就是将子查询括在 中()
:
INSERT INTO c VALUES (
(SELECT ID from a where Name='Me'),
(SELECT ID from b where Class ='Math')
)