如何避免左连接表显示重复行?

时间:2017-11-29 07:47:06

标签: mysql

在尝试总结数量时,我遇到了查询问题。

此购物车项目表存储了id_cart和id产品

enter image description here

此订单表存储了id_cart和其他id可能包括在内,例如供应商。此表用于跟踪订单记录并向供应商发送通知。

enter image description here

错误的结果。预期输出= 1,1,1

enter image description here

SELECT  id, id_product, SUM(qty) 
from cart_item 
left join Orderp using(id_cart) 
group by id_product

http://sqlfiddle.com/#!9/07bf57/1

由于订单表中的重复id_cart导致的问题。我怎么处理这个?任何使其有效的解决方案?感谢。

2 个答案:

答案 0 :(得分:1)

尝试以下查询

SELECT
  i.id_product,
  p.name productname,
  b.id_branch,
  b.branchname,
  SUM(i.qty)
from cart_item i
left join (SELECT DISTINCT id_cart,id_branch FROM Orderp) o on o.id_cart=i.id_cart
left join product p on i.id_product=p.id_product
left join catalog c on c.id_product=p.id_product and c.id_branch=o.id_branch
left join branch b on b.id_branch=o.id_branch
group by
  i.id_product,
  p.name,
  b.id_branch,
  b.branchname

Orderp表中的主要问题,因为它包含一个购物车的两个不同订单(DISTINCT id_cart,id_branch有帮助)。并且您需要id_branch catalogand c.id_branch=o.id_branch)使用第二个条件。

SQL小提琴 - http://sqlfiddle.com/#!9/f32d5f/16

我认为您可以在任何地方INNER JOIN使用LEFT JOIN

SELECT
  i.id_product,
  p.name productname,
  b.id_branch,
  b.branchname,
  SUM(i.qty)
from cart_item i
join (SELECT DISTINCT id_cart,id_branch FROM Orderp) o on o.id_cart=i.id_cart
join product p on i.id_product=p.id_product
join catalog c on c.id_product=p.id_product and c.id_branch=o.id_branch
join branch b on b.id_branch=o.id_branch
group by
  i.id_product,
  p.name,
  b.id_branch,
  b.branchname

答案 1 :(得分:1)

您的数据或数据模型中存在错误

INSERT INTO OrderP(`id_order`,`id_cart`)VALUES(1, 1);
INSERT INTO OrderP(`id_order`,`id_cart`)VALUES(2, 1);

id_cart = 1有2行,所以当将cart_item加入orderp时,“自然连接”会使每一行加倍。

在orderp中使用内连接到不同的列更好,因为现在每个cart_item在orederp中只有一行。

SELECT id_product, sum(qty)
from cart_item ci
left join Orderp o on ci.id_cart = o.id_order
GROUP BY id_product

http://sqlfiddle.com/#!9/07bf57/13