このようなものが動作する可能性があります。どちらかで同じPRODUCT_IDのために複数の行から生じる重複を避けることが重要であることを指摘して民主党員のワシの目に
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;
ありがとう:私は私が得ているものを説明するためにいくつかのサンプルデータを追加しました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
@Demsは、例を更新しました。ありがとう。 – Oldskool
これは、product_idが各ウェアハウス表内で一意であることを前提としています(OPによって暗示されていますが、明記されていません)。+1 – MatBailie