我不太确定如何提出这个问题以保持它的意思,同时仍然提供足够的信息。如果任何人需要更多信息/表格让我知道,我将很乐意编辑。
我正在尝试查询数据库,需要连接几个表来获取我想要的数据。
查询是:显示供应商x中两个日期之间售出的商品数量以及当前库存中有多少商品。
这个的SQL如下:
SELECT p.id as product_id, p.description as description, SUM(col.quantity) as qty, SUM(s.stocklevel) as stocklevel, sup.name as supplier from products as p
LEFT JOIN customerorderlines as col on col.product_id = p.id
LEFT JOIN customerorders as co on co.id = col.customerorder_id
LEFT JOIN stock as s on s.product_id = p.id
LEFT JOIN suppliers as sup on sup.id = p.supplier_id
WHERE co.orderdate BETWEEN '2009-07-01' AND '2009-08-01'
AND p.supplier_id = 51
GROUP by col.product_id
ORDER by SUM(col.quantity)
DESC
这是它重新调整的行之一:
product_id description qty stocklevel supplier
24376 Streaker Wax Paper Strips 330 3510 Rand Rocket Ltd
注意stocklevel返回3510。
现在让我们自己看一下:
SELECT SUM(stocklevel) from stock where product_id = 24376
SUM(stocklevel)
90
凭借我有限的mysql知识,我不知道为什么会这样做。任何建议都非常感激。
提前致谢。
答案 0 :(得分:1)
您最有可能多次计算几个product_id的库存水平。
一种解决方案是预先计算每个product_id的stocklevel,并将其与原始查询结合起来。
SELECT p.id as product_id
, p.description as description
, SUM(col.quantity) as qty
, sl.stocklevel as stocklevel
, sup.name as supplier
from products as p
INNER JOIN (
SELECT product_id, SUM(stocklevel) as stocklevel
from stock
GROUP BY product_id
) sl ON sl.product_id = p.product_id
LEFT JOIN customerorderlines as col on col.product_id = p.id
LEFT JOIN customerorders as co on co.id = col.customerorder_id
LEFT JOIN stock as s on s.product_id = p.id
LEFT JOIN suppliers as sup on sup.id = p.supplier_id
WHERE co.orderdate BETWEEN '2009-07-01' AND '2009-08-01'
AND p.supplier_id = 51
GROUP by col.product_id, sl.stocklevel
ORDER by SUM(col.quantity) DESC
答案 1 :(得分:0)
SELECT prod.id as product_id, prod.description as description,
SUM(col.quantity) as qty, SUM(sup.stocklevel) as stocklevel,
sup.name as supplier, sup.id
FROM product prod
INNER join suppliers sup as sup.id = prod.supplier_id
LEFT join stock stk as stk.product_id = prod.id
LEFT JOIN customerorderlines as col on col.product_id = prod.id
LEFT JOIN customerorders as co on co.id = col.customerorder_id
WHERE co.orderdate BETWEEN '2009-07-01' AND '2009-08-01'
GROUP BY sup.id, prod.id
ORDER by SUM(col.quantity) DESC