脚本1
select supplier.suppl_no, name, count(art_no) TotalArticles
from article, supplier
where article.suppl_no = supplier.suppl_no and supplier.suppl_no = 20009
group by supplier.suppl_no, name;
结果:TotalArticles = 51
脚本2
select supplier.suppl_no, name, count(ord_no) TotalOrders
from orders, supplier
where orders.suppl_no = supplier.suppl_no and supplier.suppl_no = 20009
group by supplier.suppl_no, name;
结果:TotalOrders = 74
现在,我想将上面两个脚本合并为一个,如下所示。
脚本3
select article.suppl_no, name, count(art_no) "TotalArticles", count(ord_no) "TotalOrders"
from article, supplier, orders
where article.suppl_no = supplier.suppl_no and supplier.suppl_no = orders.suppl_no and supplier.suppl_no = 20009
group by article.suppl_no, name
结果:TotalArticles = 3774(预期51与第一个脚本一样)
结果:TotalOrders = 3774(如第二个脚本中预期的74)
所以,在这里,对于TotalArticles和TotalOrders,它给了我51 * 74 = 3774的结果。你能帮我弄清楚我在脚本3中做了什么错吗?非常感谢。
答案 0 :(得分:1)
您有一对多关系,因此请加入多重行。使用distinct
:
select a.suppl_no, name, count(distinct art_no) "TotalArticles", count(distinct ord_no) "TotalOrders"
from article a inner join supplier s on (a.suppl_no = s.suppl_no) inner join orders o on (s.suppl_no = o.suppl_no)
where s.suppl_no = 20009
group by a.suppl_no, name;
或者在with
声明中生成计数:
with co as (
select s.suppl_no, name, count(ord_no) TotalOrders
from orders o inner join supplier s on (o.suppl_no = s.suppl_no)
where s.suppl_no = 20009
group by s.suppl_no, name),
ca as (
select s.suppl_no, name, count(art_no) TotalArticles
from article a inner join supplier s on (a.suppl_no = s.suppl_no)
where s.suppl_no = 20009
group by s.suppl_no, name)
select s.suppl_no, ca.TotalArticles, co.TotalOrders
from supplier, ca, co
where s.suppl_no = 20009;
在两者中你应该使用隐式连接,别名也使查询更具可读性
答案 1 :(得分:0)
试试这个。
select a.suppl_no,name,
count(a.art_no) "TotalArticles",
count(o.ord_no) "TotalOrders"
from article a
inner join on supplier s on a.suppl_no = s.suppl_no and s.suppl_no = 20009
inner join on orders o on o.suppl_no = s.suppl_no
group by article.suppl_no, name