处理一些sql。我只想到一个问题,如果需要更多细节,请告诉我。
执行sql查询时:
select o.prodid, p.prodname, sum(o.qtysold) as "TOTAL SALES"
from orderline o
inner join product p
on o.prodid = p.prodid
group by o.prodid, p.prodname
order by 3;
我得到以下数据:
PRODID PRODNAME TOTAL SALES
39 Coffee Table 1
33 Large Desk 1
34 Hallway Table 2
37 Zzz King Size Single Bed 2
38 Bedside Lamp 4
31 Lounge Chair 5
36 Lamp Stand (Tall) 7
35 Kitchen Stool 17
这些结果准确反映了表格顺序线中的实际值。
但是,当我执行此查询时:
select o.prodid, p.prodname, sum(o.qtysold) as "TOTAL SALES"
from orderline o
inner join product p
on o.prodid = p.prodid
inner join allocation a
on a.prodid = p.prodid
inner join qualitycheck q
on q.prodid = a.prodid
having avg(q.score) >= 2
group by o.prodid, p.prodname
order by 3;
我得到以下数据:
PRODID PRODNAME TOTAL SALES
33 Large Desk 3
31 Lounge Chair 15
结果是准确的,因为正确的产品已被退回,但数据错误,因为出售的数量因我根本不理解的原因而增加了三倍。任何帮助和解释为什么会发生这种情况将不胜感激。
Reubs
答案 0 :(得分:1)
如果删除组并运行没有聚合的查询,您将看到原因。
select o.prodid, p.prodname, o.qtysold, q.score
from orderline o
join product p
on o.prodid = p.prodid
join allocation a
on a.prodid = p.prodid
join qualitycheck q
on q.prodid = a.prodid
order by 3;
两个新表的连接产生了一个笛卡尔积,并且行数增加了三倍。两个新连接之一的连接条件需要添加另一个谓词以消除重复。