Reputation: 481
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`
Upvotes: 0
Views: 75
Reputation: 891
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
Upvotes: 3
Reputation:
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`;
| or_buyer_id | orders | product |
|-------------|--------|---------|
| 21 | 1 | 2 |
Upvotes: 0