[英]Select data from 3 tables in sql
我需要从3个表中选择数据。
请检查样本表和预期输出。
还有下面的小提琴链接。
表格1
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
表2
Name | qty1
--------+----------
A1 | 1
B1 | 2
D1 | 3
F1 | 4
表3
Name | qty2
--------+----------
A1 | 5
B1 | 6
J1 | 7
预期产量
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
查询:
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;
两个left joins
似乎可以解决问题:
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
与SQL Fiddle中的full join
联接不同, left join
联接如果在左表中匹配,则仅返回右表中的行。
尝试以下查询:
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
看起来您只需要在输出列表中选择数量。 如果值分别不在table2或table3中,则它将为qty2和qty3返回NULL。
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
您可以尝试以下方法;
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.