MySQL查询按月获取特定项目的数据

时间:2016-12-02 04:03:52

标签: php mysql

好的,我有一张桌子3桌子(Orders,Order_details,Products)

订单

id  |  order_date
1   |  March-01-13
2   |  March-02-13
3   |  April-01-13
4   |  May-01-13
5   |  June-01-13
and so on.....

ORDER_DETAILS

id  |  order_id  |  product_id | total_price
1         1            1            100     /*mouse*/
2         1            3            200    /*monitor*/
3         2            2            50     /*keyboar*/
4         2            3            200    /*monitor*/
and so on....

产品

id  |  title
1      mouse
2      keyboard
3      monitor
and so on...

这是我的SQL查询,提供意外输出

SELECT title, SUM(total_price) as total_price, orders.order_date as date
FROM products
LEFT JOIN order_details
ON order_details.product_id=products.id
LEFT JOIN orders
ON orders.id=order_details.order_id
WHERE title='monitor'                    /*this is just a try, prod_id should be the one*/
GROUP BY MONTH(date)
ORDER BY total_price DESC LIMIT 10

我想得到的是所有月份的product_id的total_price

预期输出

title    | total_price | date
monitor      400         March

2 个答案:

答案 0 :(得分:1)

使用GROUP BY时,SELECT列表中的所有字段都需要聚合,或者成为GROUP BY的一部分。因此,尝试将“title”添加到组中,并将MONTH函数添加到SELECT列表中的order_date,如下所示:

SELECT title, SUM(total_price) as total_price, MONTH(orders.order_date) as date
FROM products
LEFT JOIN order_details ON order_details.product_id=products.id
LEFT JOIN orders ON orders.id=order_details.order_id
WHERE title='monitor'                   
GROUP BY title, date
ORDER BY total_price DESC LIMIT 10

这将获得每个月每个产品的total_price。

答案 1 :(得分:0)

你想要这样的东西吗?

SELECT p.title, SUM(total_price) as total_price
FROM products p LEFT JOIN
     order_details od
     ON od.product_id = p.id LEFT JOIN
     orders o
     ON o.id = od.order_id
GROUP BY p.title
ORDER BY total_price DESC
LIMIT 10;

我不明白为什么你的样本输出会有一个月的时间。