简体   繁体   中英

How to use multiple group by with inner join in mysql

I have two tables one is orders and second is order_product in which i have to find our total number of orders and total number of product in corresponding to buyer id.I have find out the total number of product correctly but i was unable to find out the total number of orders.Below is my table structure.

orders:

........................
order_id   or_buyer_id
.......................
  1           21

order_product

.................................
op_id  op_order_id  op_buyer_id
.................................
  1       1          21
  2       1          21

I want this output for this i have applied below query but it returns right value of product and wrong value of orders.

..................................
 or_buyer_id    orders    product
.................................
    21            1        2

But i am getting this from below query

...............................
or_buyer_id  orders  product
...............................
   21         2       2

my query:

SELECT o.`or_buyer_id`, count(o.`or_buyer_id`) as orders, count(op.op_buyer_id) as product FROM `orders` as o inner JOIN order_product as op on op.op_order_id=o.order_id and o.or_buyer_id = op.op_buyer_id group by o.`or_buyer_id`

Check out the following link explains how to get this done:

MySQL INNER JOIN with GROUP BY clause

http://www.mysqltutorial.org/mysql-inner-join.aspx

SELECT 
    T1.orderNumber,
    status,
    SUM(quantityOrdered * priceEach) total
FROM
    orders AS T1
        INNER JOIN
    orderdetails AS T2 ON T1.orderNumber = T2.orderNumber
GROUP BY orderNumber;

so the answer to your query would look like this:

SELECT 
    ord.or_buyer_id,
    count(DISTINCT ord.or_buyer_id) as orders,
    count(op.op_id) as product 
FROM 
    orders as ord
inner JOIN 
    order_product as op  
ON 
    op.op_order_id=ord.order_id 
and 
    ord.or_buyer_id = op.op_buyer_id
group by 
    ord.or_buyer_id

You just need to select or_buyer_id and group by it, and add extra join condition to match or_buyer_id between the two tables:

SELECT o.`or_buyer_id`,
  count(DISTINCT o.`or_buyer_id`) as orders,
  count(op.op_id) as product 
FROM `orders` as o
inner JOIN order_product as op  on op.op_order_id=o.order_id 
                               and o.or_buyer_id = op.op_buyer_id
group by o.`or_buyer_id`;

demo

| or_buyer_id | orders | product |
|-------------|--------|---------|
|          21 |      1 |       2 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM