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,
我的想法在这里, 我想按供应商 ID 显示统计信息,当我传递供应商 ID 时,它会显示该供应商提供的商品销售统计信息,
但上面的查询有时会返回空值,而且执行时间太长,大约 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
最佳答案
没有 stockID 的 tblstockhistory 是否存在。如果没有,您可以将其转换为内部联接,这会有所帮助。
例如
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
最后,如果这个查询非常重要,那么您可以创建汇总表并定期更新它们。
关于sql - mysql group by date with multiple join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4431466/