Left join, sum and count group by

后端 未结 3 1181
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 04:55

I have 3 tables: goods, store and pics. In the first table goods titles are stored. In the second - balance of goods in different stocks, in the third - links to goods pictures.

3条回答
  •  情书的邮戳
    2021-02-04 05:50

    Your issue is that when you have two (or more) store rows and two (or more) pics rows for a single goods row, you end up with the product of all the combinations of rows.

    To fix this, do your aggregation before joining:

    SELECT 
      good.id, 
      good.title, 
      IFNULL(s.storerest, 0) AS storerest, 
      IFNULL(p.picscount, 0) AS picscount
    FROM goods 
    LEFT JOIN (
      SELECT goodid, sum(rest) AS storerest
      FROM store
      GROUP BY goodid
    ) s ON (goods.id = s.goodid) 
    LEFT JOIN (
      SELECT goodid, count(id) AS picscount
      FROM pics
      GROUP BY goodid
    ) p ON (goods.id = p.goodid) 
    

提交回复
热议问题