Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select 2 columns from 3 tables

I have 3 tables:

Table t1:     Table t2:     Table t3:     
+----+----+   +----+----+   +----+----+   
| i1 | i2 |   | i2 | c2 |   | i1 | c1 |   
+----+----+   +----+----+   +----+----+   
|  1 | 22 |   |  11| cc |   |  1 | e  |   
|  2 | 33 |   |  22| bb |   |  2 | f  |   
|  3 | 11 |   |  33| aa |   |  3 | g  |   
+----+----+   +----+----+   +----+----+   

and I want to select the colum c2 from t2 and c1 from t3 using the table t1 with the columns i1 and i2 and the result would be thins:

requested Tabel:     
+----+----+   
| c1 | c2 |   
+----+----+   
|  e | bb |   
|  f | aa |   
|  g | cc |   
+----+----+   

I did a select with a union like this:

select pve.c1
from dbo.t3 as pve
join dbo.t1 as v
on pve.i1 = v.i1
union
select vse.c2
from dbo.t2 as vse
join dbo.t1 as e
on vse.i2 = e.i2

and the result is this:

resulted Tabel:     
+----+
| i1 |
+----+
|  e |
|  f |
|  g |
|  bb|
|  aa|
|  cc|
+----+

Thanks!

like image 570
XandrUu Avatar asked Jan 15 '23 18:01

XandrUu


1 Answers

try this,

SELECT  c.c1, b.c2
FROM    t1 a
            INNER JOIN t2 b
                on a.i2 = b.i2
            INNER JOIN t3 c
                on a.i1 = c.i1

SQLFiddle Demo

like image 116
John Woo Avatar answered Jan 25 '23 06:01

John Woo