简体   繁体   中英

how to “insert into table (col1, col2) values (select max(id) from table2, select id from table3); ”?

I am trying to create a many-many relationship between the max(id) in table1 with all the ids in table2, using a lookup table called table1_table2.

Ultimately so that the rows in table1_table2 will be:

table1_id, table2_id
30, 1
30, 2
30, 3
...
30, 10000

How can I do this?

I have tried

insert into insert into table1_table2 (table1_id, table2_id) 
   values (select max(id) from table2, select id from table3); 

and

insert into insert into table1_table2 (table1_id, table2_id) 
   select max(table1_id), table2_id from table1 
      join table1_table2 on table1_table2.table1_id = table1.id 
      outer join table1_table2 on table1_table2.table2_id = table2.id; 

But neither seem to work

You have 3 tables, I see. I guess you mean this:

insert into table1_table2 (table1_id, table2_id) 
   SELECT
         (select max(id) from table2)            --- or perhaps: from table1 ?
       , id
   FROM table3                                   --- or perhaps: FROM table2 ?

It sounds like this is what you want:

INSERT INTO table1_table2 (table1_id, table2_id) 
    SELECT MAX(table1.id), table2.id FROM table1, table2 GROUP BY table2.id;

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