如何通过 MySQL 通过在公共日期和产品密钥以及特定维度上加入多个单独的 table 来创建交易主文件 table?

How to create a transactional master table via MySQL by joining multiple separate tables on common date and product key plus specific dimensions?

我正在应对以下挑战:

我有多个(稀疏的)table,它们都共享一个共同的日期字段 + 共同的“product_id”。此外,每个 table 都有一个附加字段,用于跟踪产品的特定类型的交易数据,例如“售出数量”、“购买数量”、“received_support_requests”等。

Table 1

DATE PRODUCT ID UNITS SOLD
2022-01-01 1 10
2022-01-02 2 40

Table 2

DATE PRODUCT ID UNITS PURCHASED
2022-01-01 2 456
2022-01-04 5 34

Table 3

DATE PRODUCT ID RECEIVED SUPPORT REQUESTS
2022-01-04 5 2
2022-01-05 2 1

我的目标是以某种方式加入所有这些tables以便我得到一个大师table 显示每个产品在特定日期发生的情况,如下所示 using MySQL:

DATE PRODUCT ID UNITS SOLD UNITS PURCHASED RECEIVED SUPPORT REQUESTS
2022-01-01 1 10 0 0
2022-01-01 2 0 456 0
2022-01-02 2 40 0 0
2022-01-04 5 0 34 2
2022-01-05 2 0 0 1

table个都很长 > 50000 并包含大量产品 > 3000

我首先考虑构建一种(“日期”-“产品 ID”)脚手架,然后将所有 table 连接到这个脚手架 table。不幸的是,每个日期与每个产品的组合变得太大了。

您将如何以更有效的方式完成这样的连接?

SELECT date, 
       product_id,
       COALESCE(table1.amount, 0) sold,
       COALESCE(table2.amount, 0) purchased,
       COALESCE(table3.amount, 0) supported
FROM ( SELECT date FROM table1 
       UNION
       SELECT date FROM table2 
       UNION
       SELECT date FROM table3 ) dates
CROSS 
JOIN ( SELECT product_id FROM table1 
       UNION
       SELECT product_id FROM table2 
       UNION
       SELECT product_id FROM table3 ) products
NATURAL LEFT JOIN table1
NATURAL LEFT JOIN table2
NATURAL LEFT JOIN table3
HAVING sold + purchased + supported;