如何获取mysql中每个订单的订购项数和成本金额

时间:2018-02-02 18:55:18

标签: mysql jointable

我有两张桌子

顺序:

order_id |  order_date | order_by
----------------------------------
1          2018-01-05    suraj    
2          2018-01-06    sumanta

order_detail:

order_detail_id  | order_id  |  item_id  | item_cost
-----------------------------------------------------
1                     1           23         100    
2                     1           27         200    
3                     2           16         300    
4                     2           17         100    
5                     2           10         400

如何从mysql

中的上表中获取此数据
order_id  |  order_date  | order_by   | no_of_item  | order_cost
----------------------------------------------------------------
1           2018-01-05      suraj           2           300    
2           2018-01-06      sumanta         3           700

3 个答案:

答案 0 :(得分:1)

加入两个表,并与GROUP BY汇总。

SELECT t1.order_id, t1.order_date, t1.order_by, count(*) as no_of_items, sum(t2.item_cost) as order_cost
FROM order t1
    INNER JOIN order_detail t2
        ON t1.order_id = t2.order_id
GROUP BY t1.order_id, t1.order_date, t1.order_by;

答案 1 :(得分:0)

SELECT o.order, o.order_date, o.order_by, COUNT(*), SUM(od.item_cost)
FROM order o JOIN order_detail od ON(o.order_id=od.order_id)
GROUP BY o.order_id, o.order_date, o.order_by;

我觉得我在做某人的家庭作业

答案 2 :(得分:0)

使用SQL查询。

SELECT o.order_id, o.order_date, o.order_by, 
COUNT(*) as no_of_item, SUM(od.item_cost) as order_cost 
FROM order o INNER JOIN order_detial od ON o.order_id = od.order_id
GROUP BY o.order_id, o.order_date, o.order_by;