我有两个表,一个是订单,第二个是 order_product ,其中我必须找到与买家ID对应的订单总数和产品总数。我已经找到正确的产品总数,但我无法做到 找出订单总数。下面是我的表结构。
订单
........................
order_id or_buyer_id
.......................
1 21
order_product
.................................
op_id op_order_id op_buyer_id
.................................
1 1 21
2 1 21
我想要此输出,我已经应用了以下查询,但它返回 正确的产品价值和错误的订单价值。
..................................
or_buyer_id orders product
.................................
21 1 2
但我从下面的查询中得到这个
...............................
or_buyer_id orders product
...............................
21 2 2
我的疑问:
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`
答案 0 :(得分:3)
查看以下链接说明如何完成此操作:
带有GROUP BY子句的MySQL INNER JOIN
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;
所以你的查询的答案如下:
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
答案 1 :(得分:0)
您只需选择or_buyer_id
并按其分组,并添加额外的加入条件以匹配两个表之间的or_buyer_id
:
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 |