left join创建多行,按分组或不同的

bjg7j2ky  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(330)

所以我试着左键联接一个表来检查一个商店是否有一个正在运行的compign,但是如果有匹配的话,行似乎会重复。
我尝试使用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


但如果我加上

GROUP BY ShopID

它返回这个

所以突然间,第一家店“1号店”的“黑色星期五”不见了。我也尝试过不同的没有任何运气,我现在有点困惑。我错过了什么?
向约翰问好

5kgi1eie

5kgi1eie1#

使用group by cluase和max aggregation,因为重复的列值会为description、campeign\u id和shop\u 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

相关问题