mysql group by date with multiple join

时间:2010-12-13 17:13:41

标签: sql mysql

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表的参考),并且我有Stock表包含StockID,ProductCode, 我有tblbasket表,在这里维护ProductCode,

我的想法在这里, 我想通过supplierID显示thw统计数据,当我通过供应商ID时,显示show,此供应商提供商品销售统计数据,

但是上面的查询有时返回null值,并且执行需要太多时间,大约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

2 个答案:

答案 0 :(得分:1)

如果没有stockID,是否存在tblstockhistory。如果不是,您可以将其转换为内部联接,这可以提供帮助。

e.g。

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

最后,如果此查询快速变得非常重要,您可以创建汇总表并定期更新它们。

答案 1 :(得分:0)

重新编写group by子句,然后重试

group by 
    tba.UpdatedDate, tsh.SupplierID

您在查询中提到了ProductCode,但是如果您想要显示ProductCode然后将其添加到group by子句中,或者将其从select子句中删除,则在您想要的'结果'中没有提到。