Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO double select - how?

Tags:

sql

mysql

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?

like image 254
dante Avatar asked Oct 17 '25 19:10

dante


2 Answers

If each of the SELECT subqueries returns exactly one value, you can use INSERT INTO ... SELECT syntax:

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

Otherwise you need to specify a condition on which the two tables are joined together and perform JOIN in the SELECT query of the INSERT statement.

like image 104
Giorgos Betsos Avatar answered Oct 20 '25 09:10

Giorgos Betsos


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' 
like image 38
TheGameiswar Avatar answered Oct 20 '25 09:10

TheGameiswar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!