简体   繁体   English

对于每个循环SQL

[英]For each loop SQL

Table1 表格1

id ID

Table2 表2

id ID

Table3 表3

id|table1_id|table2_id id | table1_id | table2_id

I need the SQL (using MySQL) statement for: 我需要以下SQL(使用MySQL)语句:

for each row in table1 {
   for each row in table2 {
       insert in table3 values table1.id, table2.id;
}

Does an insert/select statement exists ? 是否存在插入/选择语句? Or do I have to use a loop ? 还是我必须使用循环?

You don't need to use loops at all. 您根本不需要使用循环。 You should be thinking in terms of SETS when using a relational database. 使用关系数据库时,您应该考虑SETS。

Here is the correct way to achieve this. 这是实现此目的的正确方法。 First using the CROSS JOIN to create a cartesian set of all the combinations of ids from table1 and table2. 首先使用CROSS JOIN创建来自table1和table2的所有id组合的笛卡尔集合。 Then inserting that entire set into table3 Note: I am assuming Table3 ID is an auto-number. 然后将整个集合插入到table3中。注意:我假设Table3 ID是一个自动编号。

INSERT INTO TABLE3 (TABLE1_ID,TABLE2_ID)
SELECT  T1.ID
        ,T2.ID
FROM    TABLE1 T1
CROSS JOIN
        TABLE2 T2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM