使用 2 个右连接和分组依据的查询不会显示正确的结果
有人可以帮我解决这个问题吗?
我有 3 个表:订单、客户和产品。
我需要有每个客户+每个产品的订单数量列表。 像这样:
Customer A Product X 4
Customer A Product Y 0
Customer A Product Z 0
Customer B Product X 2
Customer B Product Y 0
Customer B Product Z 1
Customer C Product X 0
Customer C Product Y 0
Customer C Product Z 8
我尝试了这样的查询:
SELECT c.Name, p.Name, COUNT(o.OrderID)
FROM orders AS o
RIGHT JOIN customers AS c ON c.CustomerID=o.CustomerID
RIGHT JOIN products AS p ON p.ProductID=o.ProductID
GROUP BY c.Name, p.Name
但我无法让它工作!
它只显示计数器>0的组合(其中“订单”中有记录)。但是只有 1 个连接它才起作用,然后它确实正确显示计数器为 0 的记录。(在本例中,没有出售产品 Y,但我确实希望在组合列表中看到 Y)
有什么想法吗?
Can anybody help me with this query ?
I have 3 tables : orders, customers and products.
I need to have a list of the number of orders for each customer + for each product.
Like this:
Customer A Product X 4
Customer A Product Y 0
Customer A Product Z 0
Customer B Product X 2
Customer B Product Y 0
Customer B Product Z 1
Customer C Product X 0
Customer C Product Y 0
Customer C Product Z 8
I tried a query like this :
SELECT c.Name, p.Name, COUNT(o.OrderID)
FROM orders AS o
RIGHT JOIN customers AS c ON c.CustomerID=o.CustomerID
RIGHT JOIN products AS p ON p.ProductID=o.ProductID
GROUP BY c.Name, p.Name
but I can't get it to work !
It only displays the combinations where the counter>0 (where there are records in 'orders'). But with only 1 join it DOES work, and then it DOES correctly display the records with a counter of 0. (In this example there are no products Y sold, but I do want to see Y in the list of combinations)
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用交叉连接。这是 Oracle SQL,所以不确定它是否适用于 mysql。
Use a cross join. This is Oracle SQL, so not sure if it'll work for mysql.
您希望使用外连接,让客户成为查询的左侧,然后让订单成为剩余查询的左侧,因为您要根据客户和订单进行分组。
我更喜欢左外连接,因为它们更好地映射到您的实际含义:
You want to use outer joins and have the customers be the left side of the query, then the orders to be the left side of the remaining query, because it's the customers then orders you want to group by.
I prefer left outer joins because they map better to what you actually mean:
如果它仍然不起作用,你可以这样做,这应该是等效的
(我在这里猜测..正如我所说我手头没有sql)
If it still does not work you can do like this, which should be an equivalent
(I am guessing here .. as I said I have no sql at hand)