MySQL - 根据其他表的标准自行连接表

时间:2017-09-14 21:06:17

标签: mysql join

以下是我要解决的问题:

表1 包含这些日期的产品ID,日期和价格,表2 具有产品属性。

我希望能够根据一组属性比较同一日期不同产品的客户价格。我很容易得到“简单”产品的产品/日期/价格清单,以及“高级”产品(见下文)。

我希望能够加入这两个表,使输出看起来像:

  

[客户] [产品] [日期] [SIM_PROD] [SIM_PRICE] [ADV_PROD] [ADV_PRICE]

就我而言,这是

SELECT b.NAME AS ‘CLIENT’, a.NAME AS ‘SIMPLE_PRODUCT’, t1.DATE AS ‘DATE’, t1.PIVOT_PRICE AS ‘SIMPLE_PRICE’
FROM TABLE1 t1
LEFT JOIN PRODUCT a
ON t1.PRODUCT_ID = a_PRODUCT_ID
LEFT JOIN CLIENTS b
ON a.PARTNER_ID = b.PARTNER_ID
WHERE a.CRITERIA = TRUE;


SELECT b.NAME AS ‘CLIENT’, a.NAME AS ‘ADV_PRODUCT’, t2.DATE AS ‘DATE’, t2.PIVOT_PRICE AS ‘ADV_PRICE’
FROM TABLE1 t2
LEFT JOIN PRODUCT a
ON t2.PRODUCT_ID = a_PRODUCT_ID
LEFT JOIN CLIENTS b
ON a.PARTNER_ID = b.PARTNER_ID
WHERE a.CRITERIA = FALSE;

我已经能够构建类似的表格,我从TABLE1中提取价格,将其标记为t1,然后再从TABLE1中提取价格并将其标记为t2,但仅在使用TABLE1中的条件时,而不是在需要加入的表。

是否可以设置'一张桌子(EG简单)然后设置'第二个(EG高级),然后加入PARTNER_ID和DATE?

1 个答案:

答案 0 :(得分:0)

您可以加入两个子查询:

SELECT t1.client, t1.date, t1.simple_product, t1.simple_price, t2.adv_product, t2.adv_price
FROM (
    SELECT b.NAME AS CLIENT, a.NAME AS SIMPLE_PRODUCT, t1.DATE, t1.PIVOT_PRICE AS SIMPLE_PRICE
    FROM TABLE1 t1
    LEFT JOIN PRODUCT a
    ON t1.PRODUCT_ID = a_PRODUCT_ID
    LEFT JOIN CLIENTS b
    ON a.PARTNER_ID = b.PARTNER_ID
    WHERE a.CRITERIA = TRUE
) AS t1
JOIN (
    SELECT b.NAME AS CLIENT, a.NAME AS SIMPLE_PRODUCT, t1.DATE, t1.PIVOT_PRICE AS SIMPLE_PRICE
    FROM TABLE1 t1
    LEFT JOIN PRODUCT a
    ON t1.PRODUCT_ID = a_PRODUCT_ID
    LEFT JOIN CLIENTS b
    ON a.PARTNER_ID = b.PARTNER_ID
    WHERE a.CRITERIA = FALSE
) AS t2
ON t1.client = t2.client AND t1.date = t2.date

您可能需要选择其他条件并将其添加到ON条件。否则,这将在具有相同客户和日期的所有产品之间产生完整的交叉产品。

您想要的输出有一个额外的PRODUCT列,但我看不出它来自哪里。