[英]How to join 3 tables in SQL
I have 3 tables:我有 3 个表:
Table 1表格1
id | email
---+----------
1 | a@a.com
2 | b@a.com
3 | c@a.com
4 | d@a.com
Table 2表 2
order_id | email
---------+--------------
1 | a@a.com
2 | a@a.com
3 | a@a.com
4 | c@a.com
5 | c@a.com
6 | b@a.com
7 | b@a.com
Table 3表3
order_id | sku | qty
---------+----------+-----
1 | sku1 | 1
2 | sku1 | 2
3 | sku1 | 1
4 | sku2 | 3
5 | sku2 | 2
6 | sku2 | 6
7 | sku3 | 5
I want to join table 1 to table 2 and table 3.我想将表 1 连接到表 2 和表 3。
Get all rows of table 1 and table 3 sku1 + count qty by sku1 with email + count order of customer has 'sku1'获取表 1 和表 3 的所有行
I want get a result like this:我想得到这样的结果:
id | email | sku | order | orderqty
---+----------+--------+----------+--------------
1 | a@a.com | sku1 | 3 | 4
2 | b@a.com | sku1 | 3 | 5
3 | c@a.com | sku1 | 1 | 6
4 | d@a.com | sku1 | null | null
Can someone help me?有人能帮我吗? Thanks all <3谢谢大家<3
I think you want left join
s and aggregation:我想你想要left join
和聚合:
select t1.id, t1.email, 'sku1' sku, count(distinct t2.order_id) cnt_order, sum(t3.qty) orderqty
from table1 t1
left join table2 t2 on t2.email = t1.email
left join table3 t3 on t3.order_id = t2.order_id and t3.sku = 'sku1'
group by t1.id, t1.email
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.