2017-11-17 86 views
1

我在Mysql版本5.5上。我有两个表 - 产品,ordr。MySql - 从一组表中获取两组记录的总数

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

您需要在信息加入之前对其进行汇总。既然你有两个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 
+0

感谢您的快速响应。我的用例是这样的,我需要以产品的一个记录的形式得到结果集,并将总和作为记录中的列。问题是用例的简化版本。有没有办法做到这一点? – Surya

+0

@苏里亚:我意识到,一旦我回答了。用MySQL做这件事很麻烦,但它是可行的。请参阅最新的答案。 – Jacobm001