我目前有一个名为pairs_of_products的表,其中包含以下两列:
product_id_1, product_id_2
我想创建一个名为monthly_orders的临时表,它将包含以下列:
product_id, monthly_orders
然后将它加入pairs_of_products,这样我就可以得到一个包含以下列的新表
product_id_1, product_id_2, monthly_orders_1, monthly_orders_2
我不确定如何以有效的方式解决这个问题 - 尽管我确信我只想创建monthly_orders
一次。
答案 0 :(得分:1)
第1步:创建monthly_orders
。
第2步:查询它:
SELECT pp.product_id_1,
pp.product_id_2,
mo1.monthly_orders AS monthly_orders_1,
mo2.monthly_orders AS monthly_orders_2
FROM pairs_of_products pp
JOIN monthly_orders mo1
ON pp.product_id_1 = mo1.product_id
JOIN monthly_orders mo2
ON pp.product_id_2 = mo2.product_id
;
编辑添加:或者,只需一步:
WITH monthly_orders AS
( SELECT ... AS product_id,
... AS monthly_orders
FROM ...
)
SELECT pp.product_id_1,
pp.product_id_2,
mo1.monthly_orders AS monthly_orders_1,
mo2.monthly_orders AS monthly_orders_2
FROM pairs_of_products pp
JOIN monthly_orders mo1
ON pp.product_id_1 = mo1.product_id
JOIN monthly_orders mo2
ON pp.product_id_2 = mo2.product_id
;
(使用 subquery factoring )。