简体   繁体   中英

For each loop SQL

Table1

id

Table2

id

Table3

id|table1_id|table2_id

I need the SQL (using MySQL) statement for:

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.

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. Then inserting that entire set into table3 Note: I am assuming Table3 ID is an auto-number.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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