[英]Mysql Query with LEFT JOIN and having count of OrderID from another table… Stuck
This is my current query and it's working fine as I expect it. 这是我当前的查询,并且按预期工作正常。
SELECT a.ID, a.CreatedDate, a.Status, b.OrderTotal,
e.Rate, f.RouteType, f.Code, g.Country, h.Network
from orders AS a
LEFT JOIN order_details AS b ON a.ID = b.OrderID
LEFT JOIN order_routes AS d ON a.ID = d.OrderID
LEFT JOIN userrate AS e ON e.ID = d.RouteID
LEFT JOIN ratelist AS f ON f.ID = e.RateListID
LEFT JOIN country AS g ON f.CountryID = g.ID
LEFT JOIN network AS h ON f.NetworkID = h.ID
WHERE a.UserID = 16 ORDER BY a.CreatedDate DESC
However now I am trying to add another column which shows me count of appearances of each OrderID from order_routes 但是,现在我试图添加另一列,该列向我显示order_routes中每个OrderID的出现次数
My order routes look like this right now 我的订单路线现在看起来像这样
ID OrderID RouterID
1 1 1
2 1 2
3 2 2
4 2 3
5 2 5
So I want column which shows me how many appearances OrderID have in order_routes table. 所以我想要一列,该列向我显示Order_routes表中有多少OrderID外观。
I think I need sub query inside my query but when I try that it giving me error. 我想我的查询中需要子查询,但是当我尝试它给我错误时。 To let you know
让你知道
a.ID = d.OrderID a.ID = d.OrderID
e.ID = d.RouteID e.ID = d.RouteID
Please help. 请帮忙。
try this 尝试这个
SELECT a.ID, a.CreatedDate, a.Status, b.OrderTotal,
e.Rate, f.RouteType, f.Code, g.Country, h.Network, d2.cnt AS OrderCount
FROM orders AS a
LEFT JOIN order_details AS b ON a.ID = b.OrderID
LEFT JOIN order_routes AS d ON a.ID = d.OrderID
LEFT JOIN (SELECT OrderID as OrderID2, COUNT(*) AS cnt FROM order_routes GROUP BY 1) AS d2 ON a.ID = d2.OrderID2
LEFT JOIN userrate AS e ON e.ID = d.RouteID
LEFT JOIN ratelist AS f ON f.ID = e.RateListID
LEFT JOIN country AS g ON f.CountryID = g.ID
LEFT JOIN network AS h ON f.NetworkID = h.ID
WHERE a.UserID = 16 ORDER BY a.CreatedDate DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.