dante dante - 5 months ago 19
SQL Question

INSERT INTO double select - how?

I'm trying to insert two values from two select statements, something like:

INSERT INTO manytomany_relation_a_and_b_tables (a_id, b_id) VALUES
(SELECT id FROM a_table WHERE someColumnFromA="SOMETHING"),
(SELECT id FROM b_table WHERE someColumnFromB="SOMETHING");


Obviously it doesn't work, but how can I achieve effect which I want?

Answer

You also can use join,if those two tables have any thing in common..

INSERT INTO manytomany_relation_a_and_b_tables (a_id, b_id) 
VALUES 
select t1.id,t2.id
from a_table t1
join
b_table t2
on t1.something=t2.something
and t1.somecolumna='something' and t2.somecolumna='something'