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

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

INSERT INTO Table from multiple tables

mysqlsql

提问by ThingWings

Hey so I have a Junction table linking two unrelated tables. Both the tables have ID's. I need to select the IDfrom each table using WHEREwith 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 joinstatement 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 Nameand Class, the easiest method is just to enclose your subqueries in ():

假设每个表中给定的Nameand只有一个值Class,最简单的方法就是将子查询括在 中()

INSERT INTO c VALUES (
(SELECT ID from a where Name='Me'),
(SELECT ID from b where Class ='Math')
)

Demo on dbfiddle

dbfiddle 上的演示