简体   繁体   中英

Select data from 3 tables in sql

I need to select data from 3 tables.

Please check the sample tables and expected output.

And also the fiddle link below.

Table1

Name    |   Image_Name
--------+--------------
A1      |    A1.jpg
B1      |    B1.jpg
C1      |    C1.jpg
D1      |    D1.jpg
E1      |    E1.jpg
F1      |    F1.jpg
G1      |    G1.jpg
H1      |    H1.jpg
I1      |    I1.jpg
J1      |    J1.jpg

Table2

Name    |   qty1
--------+----------
A1      |    1
B1      |    2    
D1      |    3    
F1      |    4

Table3

Name    |   qty2
--------+----------
A1      |    5
B1      |    6
J1      |    7

Expected Output

Name    |   Image_Name  |  qty1   |  qty2
--------+---------------+---------+--------
A1      |    A1.jpg     |   1     |   5
B1      |    B1.jpg     |   2     |   6
D1      |    D1.jpg     |   3     |   0
F1      |    F1.jpg     |   4     |   0
J1      |    J1.jpg     |   0     |   7

Find the Fiddle here

The query:

SELECT a.Name,a.Image_Name,
    b.qty1,c.qty2
FROM Table1 a
JOIN Table2 b
    ON a.Name=b.Name
FULL JOIN Table3 c
    ON b.Name=c.Name;

Two left joins would appear to do the trick:

select  name
,       image_name
,       coalesce(t2.qty1, 0)
,       coalesce(t3.qty2, 0)
from    t1
left join 
        t2
on      t1.Name = t2.Name
left join    
        t3
on      t1.Name = t3.Name

Unlike the full join from your SQL Fiddle, a left join returns only rows from the right table if they are matched in the left table.

Try Following query:

SELECT table1.name, table1.Image_name, Table2.Qty1, Table3.Qty2
FROM table1
LEFT JOIN table2 on Table2.Name = table1.name
LEFT JOIN table3 on Table3.Name = table1.name
WHERE table2.name IS NOT NULL
 OR table3.name IS NOT NULL

It looks like you just need to select the qty in the output list. This will return NULL for qty2 and qty3 if the value is not in table2 or table3 respectively.

select name, image_name, 
(select qty1 from table2 where name = table1.name) as qty1, 
(select qty2 from table3 where name = table1.name) as qty2 
from table1

You can try the below;

Select tbl1.Name, tbl1.Image_Name, tbl2.qty1, tbl3.qty2  
from   Table1 tbl1
inner join Table2 tbl2
on    tbl1.Name = tbl2.Name
inner join Table3 tbl3
on    tbl1.Name = tbl3.Name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM