這樣的事情可能會奏效。我已經添加了一些樣本數據來說明什麼,我在得到:
create table Product_table
(Product_ID int unsigned primary key,Product_Name varchar(50) not null,
UNIQUE KEY `Product_TableUIdx1` (Product_Name));
create table Warehouse1_Table
(Product_ID int unsigned not null,Inventory1 int,
UNIQUE KEY `Warehouse1_Table_UIdx1` (Product_Id));
create table Warehouse2_Table
(Product_ID int unsigned,Inventory2 int,
UNIQUE KEY `Warehouse2_Table_UIdx1` (Product_Id));
insert into Product_table values (1,"Banana");
insert into Product_table values (2,"Apple");
insert into Product_table values (3,"Pear");
insert into Product_table values (4,"Orange");
insert into Warehouse1_Table values (1,2);
insert into Warehouse2_Table values (3,10);
insert into Warehouse2_Table values (4,5);
insert into Warehouse2_Table values (1,3);
select pt.Product_ID,pt.Product_Name,
ifnull(wt1.Inventory1,0)+ifnull(wt2.Inventory2,0) as StockTotal
from Product_table pt
left outer join Warehouse1_Table wt1 on wt1.Product_ID = pt.Product_ID
left outer join Warehouse2_Table wt2 on wt2.Product_ID = pt.Product_ID;
由於民主黨的鷹的眼睛指出,重要的是避免在同一PRODUCT_ID多行所產生的重複是很重要的兩種Warehouse1_Table或Warehouse1_Table。如果添加唯一鍵在上面DDL是不可能的,那麼你可以解決使用(有點醜陋)這樣的查詢:
select pt.Product_ID,pt.Product_Name,
ifnull(wt1.Inventory1Total,0)+ifnull(wt2.Inventory2Total,0) as StockTotal
from Product_table pt
left outer join (select w1.Product_ID,sum(w1.Inventory1) as Inventory1Total
from Warehouse1_Table w1 group by w1.Product_ID) as wt1 on wt1.Product_ID = pt.Product_ID
left outer join (select w2.Product_ID,sum(w2.Inventory2) as Inventory2Total
from Warehouse2_Table w2 group by w2.Product_ID) as wt2 on wt2.Product_ID = pt.Product_ID;
`NULL + 3 = NULL` =>你需要'IFNULL(w1.Inventory1,0)+ ISNULL(w2.Inventory2,0)` – MatBailie 2011-12-15 08:38:21
@Dems你是對的,更新的例子。謝謝。 – Oldskool 2011-12-15 08:40:13
這假定每個倉庫表中的product_id都是唯一的(這是OP所暗示的,但未說明)。+1 – MatBailie 2011-12-15 08:44:42