Mysql Select查询返回两次

时间:2018-09-05 08:25:27

标签: mysql

这是我的查询

SELECT SUM(`sales_order_products`.`quantity`) AS total
      ,SUM(`sales_order`.`total`) AS price
FROM `sales_order` AS `so`
LEFT OUTER JOIN `sales_order_products` AS `p` ON `so`.`id` = `p`.`order_id`
WHERE leasing = 0

sales_order表中,我有9条记录,在sales_order_products中,我有10条记录。 这是因为其中一个订单有2个产品。 total的结果还可以,但是price返回两次带有2个产品的订单总数。像我的sales_order表记录一样:

id  total
1   10
2   10
3   10
4   10
5   20

我的sales_order_products表如下:

id  order_id  quantity
1   1         1
2   2         1
3   3         1 
4   4         1
5   5         1
6   5         1

为什么SUM()两次返回第5条记录? LEFT OUTER JOIN语句仅从左表中获取结果,对吗?在我的情况下是sales_order。以我的理解,它应该返回total列结果,例如60,现在它返回80。我的错误在哪里?谢谢!

1 个答案:

答案 0 :(得分:0)

因为sales_order_products表中有两行是order_id = 5,所以与sales_order表中的遗嘱关系是id = 5

因此JOIN

中将完全匹配

根据您的情况,您可以使用DISTINCT删除重复项,然后使用join

CREATE TABLE sales_order(
   ID INT,
   total INT
);


INSERT INTO sales_order VALUES (1,10);
INSERT INTO sales_order VALUES (2,10);
INSERT INTO sales_order VALUES (3,10);
INSERT INTO sales_order VALUES (4,10);
INSERT INTO sales_order VALUES (5,20);

CREATE TABLE sales_order_products(
   ID INT,
   order_id INT,
  quantity INT
);


INSERT INTO sales_order_products VALUES (1,1,1);
INSERT INTO sales_order_products VALUES (2,2,1);
INSERT INTO sales_order_products VALUES (3,3,1); 
INSERT INTO sales_order_products VALUES (4,4,1);
INSERT INTO sales_order_products VALUES (5,5,1);
INSERT INTO sales_order_products VALUES (6,5,1);

查询1

SELECT
   SUM(`sales_order`.`total`) as total,
   SUM(sop.`quantity`) as total
FROM `sales_order`
LEFT JOIN (SELECT DISTINCT `quantity`,`order_id` FROM `sales_order_products`) sop
ON `sales_order`.`id` = sop.`order_id`

Results

| total | total |
|-------|-------|
|    60 |     5 |