2014-11-06 57 views
0

我期望看到每个供应商已与每个客户(间接通过分销商)完成的总美元业务的细分,其中我试图不使用语法Inner Join。我基本上不了解由如下所示的两个查询所产生的两个输出端之间的差:尝试了解查询中的NULL运算符

查询1

select customers.cust_id, vendors.vend_id, sum(OrderItems.item_price*OrderItems.quantity) as total_business from 
(((Vendors left outer join products 
on vendors.vend_id = products.prod_id) 
left outer join OrderItems 
on products.prod_id = OrderItems.prod_id) 
left outer join Orders 
on OrderItems.order_num = Orders.order_num) 
left outer join Customers 
on Orders.cust_id = Customers.cust_id 
group by Customers.cust_id, vendors.vend_id 
order by total_business 

我得到以下输出: enter image description here

QUERY2

select customers.cust_id, Vendors.vend_id, sum(quantity*item_price) as total_business from 
(((Vendors left outer join Products 
on Products.vend_id = Vendors.vend_id) 
left outer join OrderItems --No inner joins allowed 
on OrderItems.prod_id = Products.prod_id) 
left outer join Orders 
on Orders.order_num = OrderItems.order_num) 
left outer join Customers 
on Customers.cust_id = Orders.cust_id 
where Customers.cust_id is not null -- THE ONLY DIFFERENCE BETWEEN QUERY1 AND QUERY2 
group by Customers.cust_id, Vendors.vend_id 
order by total_business 

enter image description here

我不明白如何只有NULLcust_id的第一个输出关联在第二个输出时,我们得到一些非空cust_id s。为什么不第一输出包括这些非NULL cust_id

谢谢

回答

0

当你离开加入到一个表,然后在该表中筛选在where子句中,连接有效地改变成内部联接。解决方法是将过滤器应用为连接条件。

在你的第二个查询中,你所要做的就是将单词“where”改为“and”。

1

查询一个是加盟厂商和产品错误:

on vendors.vend_id = products.prod_id -- Vend_ID = Prod_ID

查询二是正确连接供应商和产品:

on Products.vend_id = Vendors.vend_id -- Vend_ID = Vend_ID

一旦是固定的,你会得到两个查询中都有相同的ID。然后,我建议您阅读Dan的答案,以便理解为什么您试图通过向链中最后一个表的列添加WHERE过滤器来消除查询中的INNER JOIN