我在Mysql 5.5版上。我有两张桌子 - 产品,ordr。
CREATE TABLE `product` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `ordr` (
`id` int(11) NOT NULL,
`product_id` varchar(45) DEFAULT NULL,
`status` varchar(45) DEFAULT NULL,
`qty` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
以下是它们的填充方式 -
insert into product values (20, 'pen');
insert into ordr values (100, 20, 'queue', 5);
insert into ordr values (110, 20, 'queue', 5);
insert into ordr values (120, 20, 'pending', 10);
insert into ordr values (130, 20, 'pending', 10);
insert into ordr values (140, 20, 'pending', 10);
我想获得两种不同状态的产品总数。对于上面数据的测试数据,我想看到10个队列数量,30个待处理数量。
当我跑步时
select p.name, sum(o.qty) as queue_qty, sum(o2.qty) as pending_qty
from product p
left outer join ordr o on o.product_id = p.id and o.status = 'queue'
left outer join ordr o2 on o2.product_id = p.id and o2.status = 'pending'
where p.id = 20;
我得到了
name - pen
queue_qty - 30
pending_qty - 60
有人可以帮我修复这个SQL吗?
答案 0 :(得分:0)
您需要在信息加入之前汇总。由于您有两个1-n关系,因此您的连接逻辑会复制信息。
select
p.name
, o.qty as qty_queue
, o2.qty as qty_pending
from
product p
join (
select
product_id
, sum(qty) as qty
from
ordr
where
ordr.status = 'queue'
group by
product_id
) o
on p.id = o.product_id
join (
select
product_id
, sum(qty) as qty
from
ordr
where
ordr.status = 'pending'
group by
product_id
) o2
on p.id = o2.product_id
group by
p.name