Left join, sum and count group by

后端 未结 3 1180
佛祖请我去吃肉
佛祖请我去吃肉 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:49

    You are joining together table 'goods' with two other tables, where these two other tables have a one-to-many relations to the 'goods' table. When they are joined, a combination of rows will results - so if there are 2 pics then store items are listed twice.

    The easiest way to solve this if you first calculate the stats of the sub-tables and then you join them and use distinct counting when counting unique items, so for example you query should really be:

    SELECT good.id, good.title, sum_rest AS storerest, count(distinct pics.id) AS picscount 
    FROM goods 
    LEFT JOIN (select goodid, sum(rest) as sum_rest from store) s ON (goods.id = s.goodid) 
    LEFT JOIN pics ON (goods.id = pics.goodid) 
    GROUP BY goods.id
    

提交回复
热议问题