将3个表联接到单个表(联接4个表)

时间:2019-04-23 02:50:54

标签: mysql sql join

我有3个销售表和1个包含所有产品ID的产品表。我需要将销售表与产品表结合起来以获取每周销售量。

Tables and how they relate

我尝试了几种不同的联接方法和联合。每当我得到错误的输出时(要么太多,要么类似交叉联接)。目前,我运行3个不同的查询,导出这些表并在excel中手动组合这些表。

我尝试过的联接示例。

SELECT p1.product, p2.week, 
       p2.sales, p2.QTY,
       p3.sales, p3.QTY, 
       p4.sales, p4.QTY
FROM products_table p1 INNER JOIN aplha_sales p2 ON p1.alpha_product_id = p2.alpha_product_id
                       INNER JOIN beta_sales p3 ON p1.beta_product_id = p3.beta_product_id
                       INNER JOIN delta_sales p4 ON p1.delta_id = p4.delta_product_id
WHERE p2.week >= '2019-04-19';

我想要一个包含以下各列的表:

Desired Output

1 个答案:

答案 0 :(得分:1)

您需要在连接中包括星期,这样您才可以从每个表中获取该星期的数据。

SELECT p1.product, p2.week, 
       p2.sales, p2.QTY,
       p3.sales, p3.QTY, 
       p4.sales, p4.QTY
FROM products_table p1 
INNER JOIN aplha_sales p2 ON p1.alpha_product_id = p2.alpha_product_id
INNER JOIN beta_sales p3 ON p1.beta_product_id = p3.beta_product_id AND p3.week = p2.week
INNER JOIN delta_sales p4 ON p1.delta_id = p4.delta_product_id AND p4.week = p2.week
WHERE p2.week >= '2019-04-19';

请注意,这只会在所有3种产品均已销售的几周内产生行。您可以使用LEFT JOIN将其中两个表的销售设置为可选。但是要使其对于所有3张XXX_sales表都是可选的,您需要与定义所需星期数的另一张表联接,然后与所有sales表一起LEFT JOIN联接。

SELECT p1.product, w.week, 
       p2.sales, p2.QTY,
       p3.sales, p3.QTY, 
       p4.sales, p4.QTY
FROM products_table p1 
CROSS JOIN (
    SELECT week FROM alpha_sales WHERE week >= '2019-04-19'
    UNION
    SELECT week FROM beta_sales WHERE week >= '2019-04-19'
    UNION
    SELECT week FROM delta_sales WHERE week >= '2019-04-19') AS w
LEFT JOIN aplha_sales p2 ON p1.alpha_product_id = p2.alpha_product_id AND p2.week = w.week
LEFT JOIN beta_sales p3 ON p1.beta_product_id = p3.beta_product_id AND p3.week = w.week
LEFT JOIN delta_sales p4 ON p1.delta_id = p4.delta_product_id AND p4.week = w.week

子查询中的UNION将合并任何销售表中的所有星期。默认情况下,UNION会删除重复项,因此每周不会有多行。