LEFT JOIN创建多行,GROUP BY或DISTINCT

问题描述 投票:0回答:1

所以我试图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

因此,第一家商店“Shop 1”突然出现“黑色星期五”。我也试过DISTINCT而没有任何运气,我现在有点困惑。我错过了什么?

最好的问候约翰

mysql join left-join
1个回答
1
投票

使用具有最大聚合的cluase组,因为您的重复列值为description,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
© www.soinside.com 2019 - 2024. All rights reserved.