LEFT JOIN创建多行,GROUP BY或DISTINCT

时间:2018-09-17 12:25:38

标签: mysql join left-join

因此,我试图左联接表以检查商店中是否有正在运转的公司,但如果有匹配项,行似乎会重复。

我尝试使用DISTINCT和GROUP BY,但是它的行为不像我想要的那样。

SELECT
    s.id AS ShopID,
    s.name,
    si.id AS shop_item_id,
    si.item_price,
    p.cat_id AS category_id,
    c.campaign_desc,
    c.campaign_type_id,
    c.shop_id AS campaign_shop_id

FROM
    shop_item si 

    JOIN
        shop s ON 
        s.id = si.shop_id
    JOIN
         product p ON 
         si.product_id = p.id
    LEFT JOIN 
        campaign_category cc ON 
        cc.category_id = p.cat_id
    LEFT JOIN 
        campaign c ON 
        c.id = cc.campaign_id AND
        c.shop_id = si.shop_id
WHERE
    si.`product_id` = 299 AND
    s.`active_shop` = 1

ORDER BY
    si.`item_price`,
    ShopID,
    c.campaign_desc DESC

enter image description here

但是,如果我添加

GROUP BY ShopID 

它返回

enter image description here

因此,第一家商店“商店1”突然缺少“黑色星期五”。我也尝试过DISTINCT,但没有任何运气,我现在有点困惑。我想念什么?

最佳问候 约翰

1 个答案:

答案 0 :(得分:1)

使用分组聚合进行最大聚合,因为重复的列值会产生空值用于描述campeign_id和shop_id,因此可以使用max来处理这些值,但是如果您共享表结构,则很容易确定其产生原因重复记录,什么是最佳解决方案

SELECT
    s.id AS ShopID,
    s.name,
    si.id AS shop_item_id,
    si.item_price,
    p.cat_id AS category_id,
    max(c.campaign_desc) as desc,
    max(c.campaign_type_id) as campaign_type_id,
    max(c.shop_id) AS campaign_shop_id

FROM
    shop_item si 

    JOIN
        shop s ON 
        s.id = si.shop_id
    JOIN
         product p ON 
         si.product_id = p.id
    LEFT JOIN 
        campaign_category cc ON 
        cc.category_id = p.cat_id
    LEFT JOIN 
        campaign c ON 
        c.id = cc.campaign_id AND
        c.shop_id = si.shop_id
WHERE
    si.`product_id` = 299 AND
    s.`active_shop` = 1
group by s.id,
    s.name,
    si.id ,
    si.item_price
ORDER BY
    si.`item_price`,
    ShopID,
    c.campaign_desc DESC