在多个 JOIN 上按月分组的查询
好的,我按月对查询进行分组,以便获得一年中每个月的记录,但我需要弄清楚如何执行此操作:基本上是在两个不同的 JOIN 语句上按月分组。如果可能的话,我试图在一个查询中获取每个子表中的数量计数或总和。我可以在 php 中循环,但我正在尝试找到一种在 mysql 中执行的方法。
这是一个示例,
SELECT SUM(purchase_quantity),SUM(sales_quantity)
FROM products p
INNER JOIN purchase_order_lines sl ON pl.product_id = p.id
INNER JOIN purchase_orders po ON pl.purchase_order_id = po.id
INNER JOIN sales_order_lines sl ON sl.product_id = p.id
INNER JOIN sales_orders so ON sl.sales_order_id = so.id
GROUP BY YEAR(so.posted & po.posted), MONTH(so.posted & po.posted)
我知道这是不可能的,而且逻辑很荒谬,这并不完全是我的数据库的结构,而只是事物如何链接以及我想要做什么的想法。我认为必须通过 SELECT 语句中的子查询来完成,但我还没有想出任何办法。我会继续考虑这个问题,但如果有人有任何想法,那就太棒了。
Ok, I'm grouping a query by month so I get a record for each month of the year, but I need to figure out how to do this: basically grouping by month on two different JOIN statements. I'm trying to get the count, or sum, of quantities in each child table if possible in one query. I could just loop through in php, but I'm trying to find a way to do in mysql.
Here's a sample
SELECT SUM(purchase_quantity),SUM(sales_quantity)
FROM products p
INNER JOIN purchase_order_lines sl ON pl.product_id = p.id
INNER JOIN purchase_orders po ON pl.purchase_order_id = po.id
INNER JOIN sales_order_lines sl ON sl.product_id = p.id
INNER JOIN sales_orders so ON sl.sales_order_id = so.id
GROUP BY YEAR(so.posted & po.posted), MONTH(so.posted & po.posted)
I know there's no way this would work, and the logic is ridiculous, and this isn't exactly the structure of my database, but just an idea of how things are linked and wwhat I'm trying to do. I'm thinking it would have to be done with subqueries in the SELECT statement, but I haven't come up with anything yet. I'll keep thinking about it, but if anyone has any ideas, that would be awesome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为你对结果进行分组,你会得到一的计数。为什么不尝试运行一个单独的语句来计算结果并运行一个单独的语句来对其进行分组。
because your grouping your result, you will get a count of one. why don't you try running a separate statement that will count the result and a separate statement to group it.