Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple column left join from table1, table2

Tags:

mysql

I have two tables: table1,table2 as given below

table1:
id   name
1    tamil
2    english
3    maths
4    science

table2:
p1 p2 p3 p4 stat name
1  2  4  3   A   raja
2  3  4  1   A   maha

my expected output is

p1       p2       p3       p4
tamil   english   science  maths
english maths     science  tamil

can some one help me to find out the exact query.That should use left outer join.

like image 488
Vigneswaran S Avatar asked Nov 30 '15 09:11

Vigneswaran S


People also ask

How do I combine two left joins?

Syntax For Left Join:SELECT column names FROM table1 LEFT JOIN table2 ON table1. matching_column = table2. matching_column; Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables.

Can you inner join on multiple columns?

Yes: You can use Inner Join to join on multiple columns. Save this answer.


2 Answers

select P1, t1.Name,P2, t3.Name, P3,t4.Name, P4 , t5.Name From Table2 T2
left join table1  t1 on 
T2.P1 = T1.Id
left join  table1  t3 on 
T2.P2 = T3.Id
left join  table1  t4 on 
T2.P3 = T4.Id
 left join  table1  t5 on 
T2.P4 = T5.Id
like image 115
CMadhu Avatar answered Nov 02 '22 12:11

CMadhu


SELECT t1.name AS p1, t2.name AS p2, t3.name AS p3, t4.name AS p4
FROM table2 tbl2 INNER JOIN table1 t1 ON tbl2.p1 = t1.id
INNER JOIN table1 t2 ON tbl2.p2 = t2.id
INNER JOIN table1 t3 ON tbl2.p3 = t3.id
INNER JOIN table1 t4 ON tbl2.p4 = t4.id

Click the link below for a running demo.

SQLFiddle

like image 37
Tim Biegeleisen Avatar answered Nov 02 '22 13:11

Tim Biegeleisen