GROUP or DISTINCT after JOIN returns duplicates

后端 未结 4 1119
深忆病人
深忆病人 2020-12-19 14:01

I have two tables, products and meta. They are in relation 1:N where each product row has at least one meta row via foreign key.

(viz. SQLf

4条回答
  •  抹茶落季
    2020-12-19 14:55

    You can use a subquery to identify the max(ID) for each product, then use that in the superquery to gather the details you want to display:

    SELECT q.product_id, meta.* from
    (SELECT product_id, max(meta.ID)
     FROM meta JOIN products ON products.id=meta.product_id 
     GROUP BY product_id) q 
    JOIN meta ON q.max=meta.id;
    

    It is not the only solution!

    A quick comparison to use of DISTINCT ON solutions suggests that it is slower (http://sqlfiddle.com/#!15/c8f34/38). It avoids a full sort on ID and prefers a sequential scan.

提交回复
热议问题