0
SELECT it.uid,it.Name,COALESCE(sum(i.Qty),0)-COALESCE(sum(s.Qty),0) as stock
FROM items it
left outer join sales_items s on it.uid=s.ItemID
left outer join inventory i on it.uid=i.uid
group by s.ItemID,i.uid,it.UID;

これは私の質問です。このクエリには 59 秒かかります。このクエリを高速化するにはどうすればよいですか?


私のテーブル - >アイテム

      UID            Item
      5089           JAM100GMXDFRUT
      5090           JAM200GMXDFRUT
      5091           JAM500GMXDFRUT
      5092           JAM800GMXDFRUT

テーブル -> sales_items

- slno        ItemID         Item              Qty
- 9           5089           JAM100GMXDFRUT    5
- 10          5090           JAM200GMXDFRUT    2
- 11          5091           JAM500GMXDFRUT    1

テーブル -> 在庫

- slno         uid            Itemname          Qty
- 102          5089           JAM100GMXDFRUT    10
- 200          5091           JAM500GMXDFRUT    15
- 205          5092           JAM800GMXDFRUT    20

このテーブルには 6000 を超える行があります

4

3 に答える 3

0

このようなものを設計する場合、クエリとスキーマは次のようになります。Idx1 インデックスに注意してください。MySql についてはわかりませんが、Sql Server は sum 関数にこれらのインデックスを使用します。これはカバーされたクエリと呼ばれます。

select  Item.ItemID, Item.Name, IsNull(sum(inv.Quantity), 0) - IsNull(sum(s.Quantity), 0) as stock
from    Item
Left Join Inventory inv
On      Item.ItemID = inv.ItemID
Left Join Sales s
On      Item.ItemID = s.ItemID
Group by Item.ItemID, Item.Name

Create Table dbo.Location
(
    LocationID int not null identity constraint LocationPK primary key,
    Name NVarChar(256) not null
)

Create Table dbo.Item
(
    ItemID int not null identity constraint ItemPK primary key,
    Name NVarChar(256) not null
);

Create Table dbo.Inventory
(
    InventoryID int not null identity constraint InventoryPK primary key,
    LocationID int not null constraint InventoryLocationFK references dbo.Location(LocationID),
    ItemID int not null constraint InventoryItemFK references dbo.Item(ItemID), 
    Quantity int not null,
    Constraint AK1 Unique(LocationID, ItemID)
);

Create Index InventoryIDX1 on dbo.Inventory(ItemID, Quantity);

Create Table dbo.Sales
(
    SaleID int not null identity constraint SalesPK primary key,
    ItemID int not null constraint SalesItemFK references dbo.Item(ItemID),
    Quantity int not null
);

Create Index SalesIDX1 on dbo.Sales(ItemID, Quantity);
于 2014-12-28T23:23:58.003 に答える
0

結合列にインデックスを配置する

sales_items アイテム ID

在庫 ID

于 2014-12-28T09:24:30.147 に答える