多表内连接查询计数异常:为何两个count结果完全一致?
问题原因与解决方法
你的两个count结果完全一致,核心是SQL语句存在两处关键问题:
1. Product表的连接条件写错了
你写的inner join product p on p.store_id = p.id是逻辑错误——这是把product自身的store_id和id做关联,完全没把product和store表关联起来。这个错误会导致不符合预期的关联结果,甚至可能把所有满足p.store_id = p.id的product行都和之前的customer行做笛卡尔积匹配。
2. 直接多表Join会产生笛卡尔积,导致计数失真
就算你把连接条件改成正确的p.store_id = s.id,直接依次Join store→customer→product也会出问题:比如一家店有12个顾客、8个商品,Join后会生成12*8=96行数据。这时count(c.store_id)和count(p.store_id)统计的都是这96行的数量,而不是真实的12个顾客和8个商品。
正确的查询写法
要得到每家店真实的顾客数和商品数,应该先分别统计顾客、商品的分组数据,再和store表关联:
select s.*, coalesce(c.customer_count, 0) as customer_count, coalesce(p.product_count, 0) as product_count from store s left join ( select store_id, count(*) as customer_count from customer group by store_id ) c on c.store_id = s.id left join ( select store_id, count(*) as product_count from product group by store_id ) p on p.store_id = s.id
用left join还能保留那些没有顾客或没有商品的门店,coalesce用来把NULL替换成0,避免结果出现空值。
内容的提问来源于stack exchange,提问作者Timo
相关产品推荐
相关产品推荐

