Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL insert to fill an associative table with conditions

I have two tables and an associative table between them (let's call them Tab1, Tab2 and ATab).

Tab1 and Tab2 have those very same fields (for example purpose) :

  • Id.
  • Name.

In my ATab, I want to insert record to associates Tab1 and Tab2 with their Ids.

In order to do so, I would like to write my query in a sql script that say something like :

I can manage to do something like :

INSERT INTO ATab(Tab1Id, Tab2Id) 
SELECT Tab1.Id, ????? 
FROM Tab1 WHERE Tab1.Name='Foo';

But I'm selecting only the Foo record of my first table...

How would I manage to perform a "double" where clause ? Is it possible ?

like image 455
Andy M Avatar asked Dec 18 '25 03:12

Andy M


1 Answers

by using AND

INSERT INTO ATab(Tab1Id, Tab2Id) 
(SELECT Tab1.Id, Tab2.Id
FROM Tab1, Tab2 WHERE Tab1.Name = 'Foo' AND Tab2.Name = 'Bar')
like image 195
epoch Avatar answered Dec 20 '25 17:12

epoch



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!