Can we use a join operation and make restrictions for different columns at the same time? I want to create a table on a Database (called DB1 in the example) based on three tables from another database (called DB2 in the example) where some columns in the new table filled with entrys when there´s a specific entry in an other column (in the example a"4" in column "attributeID" at table 2 indicates an entry in column "gender", a "5" indicates an entry in column "age"; a"7" in column "attributeID"at table 3 indicates an entry in column "street"). -> If yes, then how to do ?
Both databases are on the same server and DBMS is the same. ID1 and ID2 based on table1 in DB2; ID2, attributeID and value (where the gender or age is written depending on entry in attributeID) based on table2 in DB2; ID2 attributeID and value (where the street is written when the entry in the attributeID is a 7)based on table3 in DB2 .
Sample Data:
Table 1:
ID1 ID2
1 2
2 4
3 5
Table 2:
ID2 attributeID value
2 3 Kahtrin ->an example entry which is not relevant
2 4 miss
2 5 22
4 1 active ->an example entry which is not relevant
4 4 EMPTY/NULL
4 5 47
5 4 mr
5 5 34
5 6 Hindu ->an example entry which is not relevant
Table 3
ID2 attributeID value
2 5 20% ->an example entry which is not relevant
2 7 middlestreet 40
4 4 chinese ->an example entry which is not relevant
4 7 churchstreet 12
5 3 3Euro
5 7 EMPTY/NULL
Expected Outcome
Table 4:
ID1 ID2 gender age street
1 2 miss 22 middlestreet 40
2 4 47 churchstreet 12
3 5 mr 34
Here´s what I tried out (Made from point of view that I´m using DB1):
INSERT INTO table4
(id1,
id2,
gender,
age,
street)
SELECT t1.id1,
t1.id2,
t2.value
t2.value
t3.value
FROM db1.table1 t1
LEFT JOIN db1.table2 t2
ON t1.ID2=t2.ID2
AND value = 4 OR 5
LEFT JOIN db1.table3 t3
ON t1.ID2=t3.ID2
AND value = 7;