[英]SQL Join, right ? left ? inner?
working with mySql I would like to list all purchases that customers made on a specific cathegory of products. 使用mySql,我想列出客户在特定产品类别上进行的所有购买。
So, I had 3 tables: customers (idCustomer, Name) , cathegories (idCategory, CategoryName) and orders (idOrder, idCustomer, idCathegory, Qty, Price) 因此,我有3个表:customers(idCustomer,Name),cathegories(idCategory,CategoryName)和订单(idOrder,idCustomer,idCathegory,Qty,Price)
But I want a listing with ALL of the customers. 但我想列出所有客户。 Not only the one who bought that specific idCategory 不仅是购买该特定idCategory的人
I thought something like: 我以为是这样的:
select sum(Orders.Qty), Customers.Name
from Orders
right join Customers on Orders.idCustomer = Customer.idCustomer
where Orders.idCategory = 'Notebooks'
group by Orders.idCategory
but this statement only lists the records for customers who exists in Orders table. 但是此语句仅列出Orders表中存在的客户的记录。 And I want all of them ( the one who didnt buy, with qty =0 ) 我想要所有这些(没有购买,数量= 0的那个)
thanks in advance 提前致谢
Most people find left join
easier to follow than right join
. 大多数人发现left join
比right join
更容易遵循。 The logic for left join
is to keep all rows in the first table, plus additional information from the remaining tables. left join
的逻辑是将所有行保留在第一个表中,再加上其余表中的其他信息。 So, if you want all customers, then that should be the first table. 因此,如果您要所有客户,那应该是第一个表。
You will then have a condition on the second table. 然后,您将在第二张桌子上有一个条件。 Conditions on all but the first table should be in the on
clause rather than a where
. 除第一个表外的所有条件都应在on
子句中,而不是where
。 The reason is simple: when there is no match, then the value will be NULL
and the where
condition will fail. 原因很简单:当没有匹配项时,该值将为NULL
,而where
条件将失败。
So, try something like this: 因此,尝试这样的事情:
select sum(o.Qty) as sumqty, c.Name
from Customers c left join
Orders o
on o.idCustomer = c.idCustomer and
o.idCategory = 'Notebooks'
group by c.Name;
Finally, the group by
should have a relationship to the select
clause. 最后, group by
应该与select
子句有关系。
Try this query 试试这个查询
select sum(Orders.Qty), Customers.Name
from Customers
right join Orders on Customer.idCustomer = Orders.idCustomer and Orders.idCategory = 'Notebooks'
group by Customers.Name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.