我这里有三个表:
producttbl:
p_id p_name price
ANK001 ANKLET 200
BRC001 BRACELET 100
stocks_add:
p_id qty
ANK001 200
ANK001 50
stocks_rel:
p_id qty
ANK001 20
我在这里有这个代码(这是由@Bohemian建议的,虽然我添加了一些):
Select p.p_id, p.p_name, p.price,
`coalesce((SELECT sum(a.qty)
FROM stocks_add a GROUP BY a.p_id),0)
-coalesce((SELECT sum(r.qty)
FROM stocks_rel r GROUP BY r.p_id),0)
as stock_on_hand
from productstbl p
left join stocks_add a
on a.p_id=p.p_id
left join stocks_rel r
on r.p_id=p.p_id
GROUP BY p.p_id`
,当我执行它时,结果是这样的:
p_id p_name price stock_on_hand
ANK001 Anklet 200 230
BRC001 Bracelet 75 230
我正试图从第二和第三个表中获取手头的股票。并与产品表链接。
假设是,230应该只与ANK001。期望的输出应该是这样的:
`p_id p_name price stock_on_hand
ANK001 Anklet 200 230
BRC001 Bracelet 75 0
`
,但是第一个输出的结果告诉我们相反的方向。:(代码有什么问题?请一定要帮助我。
我不知道你的问题是什么,但这是我最容易写的:
select p.*, IFNULL(aqty,0) - IFNULL(rqty,0) AS stock_on_hand
from productstbl p
left join (
select p_id, SUM(IFNULL(a.qty,0)) as aqty
from stocks_add a
group by p_id
) AS asum
on asum.p_id = p.p_id
left join
(
select p_id, SUM(IFNULL(r.qty,0)) as rqty
from stocks_rel r
group by p_id
) AS rsum
on rsum.p_id = p.p_id;
和它实际上给出了正确的结果!这对于查询来说是一件很好的事情:)
P_ID P_NAME PRICE STOCK_ON_HAND
ANK001 ANKLET 200 230
BRC001 BRACELET 100 0
http://sqlfiddle.com/!2/3c778/3