mysqlnested-select

Mysql get SUM and COUNT value from two tables


This is my tables

table 1: orders

id  total order_date
1   200    2016-04-22
2   300    2016-04-22

table 2: order_products

 id  order product_id qty
  1    1       1       2
  2    1       2       1
  3    2       2       2
  4    2       1       2

And my result should be

tot_order total_amount  prd_qty
 2      500             7 

and my query is

    SELECT COUNT(ddo.id) AS tot_order, 
           SUM(ddo.total) AS total_amount, 
           (SELECT SUM(dop.qty) 
            FROM  order_products dop 
            WHERE dop.order=ddo.id) AS prd_qty  
    FROM orders ddo 
    WHERE DATE(ddo.`order_date`) BETWEEN '2016-04-22' AND '2016-04-22'

I can get the total_order and total_amount, but how to get prd_qty?

Thanks


Solution

  • Looks like you want to sum up the order_products into orders and then sum up the result.

    I would follow this concept in the query:

    SELECT COUNT(*) tot_order,
           SUM(os.total) total_amount,
           SUM(os.o_prd_qty) prd_qty
      FROM (       
        SELECT o.id,
               o.total,
               SUM(op.qty) o_prd_qty
          FROM orders o
          JOIN order_products op
            ON op.order = o.id
         WHERE o.order_date >= :start_date
           AND o.order_date < :end_date + INTERVAL 1 DAY
      GROUP BY o.id
           ) os
    

    If you want the separate orders with their prd_qty just run the inner query.

    I have also fixed up your date logic so that the optimiser can use an index on order_date. Generally, if you wrap a column in a function on one side of a comparison any index on that column is unusable.

    As a side note, I would take a long hard look at your naming convention. Everyone has their preferences but you should be consistent with these questions:

    Following a convention makes your database much easier to navigate and work with. Otherwise it's back to the schema when writing every query!

    Personally I generally don't abbreviate, do append the _id and don't include the table name in columns.