2010-12-13 51 views
1
SELECT 
    tba.UpdatedDate AS UpdatedDate, 
    tsh.SupplierID, 
    ts.ProductCode as ProductCode, 
    sum(tba.AfterDiscount) as AfterDiscount, 
    sum(tba.Quantity) as Quantity 
FROM 
    tblstockhistory as tsh 
    left join tblstock as ts 
    on tsh.StockID=ts.StockID 
    left join tblbasket as tba 
    on ts.ProductCode=tba.ProductCode 
     and tsh.SupplierID=49 
     AND tba.Status=3 

group by 
    tba.UpdatedDate 
ORDER BY 
    Quantity DESC 

我有供應商表,供應商ID標記在給tblstockhistory表,並且在這種tblstockhistory表包含StockID(從tblstock表引用),我有庫存表包含StockID ,產品代碼, 和我有tblbasket表,在此我保持了產品代碼,MySQL的組加入

我的想法在這裏, 我想說明的供應商ID,當我通過供應商ID,它展示秀THW統計,這個供應商提供商品銷售統計,

但上面的查詢有時會返回空值,它需要太多的時間excution,約50秒,

我是什麼樣的財產以後下面從上面查詢

Date   SupplierID, Amount, Quantity 
2010-12-12  12  12200  20 
2010-12-12  40  10252  30 
2010-12-12  10  12551  50 


2010-12-13  22  1900  20 
2010-12-13  40  18652  30 
2010-12-13  85  19681  50 

2010-12-15  22  1900  20 
2010-12-15  40  18652  30 
2010-12-15  85  19681  50 
+0

爲了提高性能,請確保您在連接中使用的所有字段都已編入索引。 – Nazariy 2010-12-13 17:23:37

回答

1

難道一個tblstockhistory沒有stockID永遠存在。如果沒有,你可以將它轉換爲可以提供幫助的內部連接。

例如

tblstockhistory as tsh 
INNER join tblstock as ts 
on tsh.StockID=ts.StockID 

你也可以考慮添加索引,如果他們目前不存在。

至少我會將以下字段編入索引,因爲它們可能會被共同加入和查詢。

  • tblstockhistory.SockID
  • tblstockhistory.SupplierID
  • tblstock.StockID
  • tblstock.ProductCode
  • tblbasket.ProductCode
  • tblBacket.Status
  • tblbasket.UpdatedDate

最後,如果這個查詢真的很重要,那麼您可以創建彙總表並定期更新它們。

+0

對於哪些字段,我應該在這裏創建索引 – Bharanikumar 2010-12-13 17:24:47

+0

StockID,是必需的,因爲stockoz只有我們拉ProductCode,ProductCode存儲在tblbasket表中, – Bharanikumar 2010-12-13 17:25:58

+0

添加了我最少索引的字段。此外,由於StockID是必需的,我一定會將其更改爲Inner Join。您可能還希望從Select中刪除ProductCode,因爲它看起來不在您的示例輸出中。 – 2010-12-13 17:37:17

0

重新寫group by子句的,然後再試一次

group by 
    tba.UpdatedDate, tsh.SupplierID 
您在查詢中提到的產品代碼,但沒有在「結果」你想,如果你想顯示的產品代碼以及然後將其添加到

按分組分組,或者將其從select子句中刪除。

+0

但這是[MySQL](http://stackoverflow.com/questions/1066453/mysql-group逐和階由/ 1066504#1066504) – 2010-12-13 17:57:59