2017-11-17 104 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