避免将 JOIN 与 OR 一起使用

问题描述 投票:0回答:1

我有两张如下表:

表_1

id_1 id_2 购买数量
1 a 20
1 a 100
2 b 21
3 c 22
4 d 23
5 e 24

表_2

id 订购 颜色
1 苹果 红色
a 苹果 红色
b 苹果 红色
3 苹果 红色
c 香蕉 黄色
d 香蕉 黄色
5 香蕉 黄色

当前使用的代码如下所示:

select
t1.id_1,
sum(t1.num_purchases) as sum_purchases,
array_agg(t2.order) as orders

from table_1 t1

left join (select id, order from table_2) t2
on t2.id = t1.id_1

group by t1.id_1

但是,由于table_2中的id来自id_1或id_2,当table_2中的id来自id_2时,行无法匹配。为了正确连接表以便同时考虑 id_1 和 id_2,代码应该如何构建?我想避免将 JOIN 与 OR 一起使用。

期望的结果应如下所示:

id 总购买量 购买数量
1 120 苹果,苹果
2 21 苹果
3 22 苹果、香蕉
4 23 香蕉
5 23 香蕉
sql presto trino
1个回答
0
投票

你能尝试一下这个吗:

select
t1.id_1,
sum(t1.num_purchases) as sum_purchases,
array_agg(t2.order) as orders
from table_1 t1
left join (select id, order from table_2) t2
on t2.id = (CASE WHEN t2.id IN (SELECT id_1 FROM table_1) THEN id_1 ELSE id_2 END)
group by t1.id_1
© www.soinside.com 2019 - 2024. All rights reserved.