试图理解Query中的NULL运算符

时间:2014-11-06 15:50:22

标签: sql sql-server

我希望看到每个供应商(通过分销商)与每个客户完成的总美元业务的细分,我试图不使用Inner Join语法。我基本上不理解下面两个查询产生的两个输出之间的区别:

查询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

我不明白在第二个输出中只有NULL cust_id与第一个输出关联,我们得到一些非NULL cust_id s。为什么第一个输出不包含这些非NULL cust_id

谢谢

2 个答案:

答案 0 :(得分:1)

Query One错误地加入了供应商和产品:

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

第二个问题是正确加入供应商和产品:

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

修复后,您将在两个查询中获得相同的ID。然后,我建议您阅读Dan的回答,了解为什么您在查询中消除INNER JOIN时尝试执行的操作是通过向最后一个表中的列添加WHERE过滤器而取消的。连锁,链条。

答案 1 :(得分:0)

当您将联接保留到表中,然后在where子句中对该表进行过滤时,该联接会有效地更改为内部联接。解决方法是将过滤器应用为连接条件。

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