简体   繁体   English

根据左联接返回不同的记录

[英]Returning distinct records based on left join

I'm having some trouble formulating a complex SQL query. 我在制定复杂的SQL查询时遇到了一些麻烦。 I'm getting the result I'm looking for and the performance is fine but whenever I try to grab distinct rows for my LEFT JOIN of product_groups, I'm either hitting some performance issues or getting incorrect results. 我得到了想要的结果,性能也很好,但是每当我为product_groups的LEFT JOIN争取不同的行时,我要么遇到一些性能问题,要么得到不正确的结果。

Here's my query: 这是我的查询:

 SELECT
    pl.name, pl.description,
    p.rows, p.columns,
    pr.sku,
    m.filename, m.ext, m.type,
    ptg.product_group_id AS group,
 FROM
    product_region AS pr
 INNER JOIN
    products AS p ON (p.product_id = pr.product_id)
 INNER JOIN
    media AS m ON (p.media = m.media_id)
 INNER JOIN
    product_language AS pl ON (p.product_id = pl.product_id)
 LEFT JOIN
    products_groups AS ptg ON (ptg.product_id = pr.product_id)
 WHERE
    (pl.lang = :lang) AND
    (pr.region = :region) AND
    (pt.product_id = p.product_id)
 GROUP BY
    p.product_id
 LIMIT
    :offset, :limit

The result I'm being given is correct however I want only distinct rows returned for "group". 得到的结果是正确的,但是我只希望为“组”返回不同的行。 For example I'm getting many results back that have the same "group" value but I only want the first row to show and the following records that have the same group value to be left out. 例如,我得到了很多具有相同“组”值的结果,但是我只希望显示第一行,而忽略具有相同组值的以下记录。

I tried GROUP BY group and DISTINCT but it gives me incorrect results. 我尝试了GROUP BY group和DISTINCT,但结果不正确。 Also note that group can come back as NULL and I don't want those rows to be effected. 另请注意,该组可以返回为NULL,并且我不希望这些行受到影响。

Thanks in advance. 提前致谢。

I worked out a solution an hour after posting this. 发布此消息后一个小时,我制定了解决方案。 My goal was to group by product_group_id first and then the individual product_id. 我的目标是先按product_group_id分组,然后再按单个product_id分组。 The requirement was that I would eliminate product duplicates and have ONE product represent the group set. 要求是我要消除产品重复,并让一个产品代表组。

I ended up using COALESCE(ptg.product_group_id, p.product_id). 我最终使用了COALESCE(ptg.product_group_id,p.product_id)。 This accounts for the fact that most of my group IDs were null except for a few dispersed products. 这解释了一个事实,除了少数分散的产品,我的大多数组ID都是空的。 In using COALESCE I'm first grouping by the group ID, if that value is null it ignores the group and collects by product_id. 在使用COALESCE时,我首先按组ID进行分组,如果该值为null,它将忽略该组并按product_id进行收集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM