【发布时间】:2022-03-15 20:03:41
【问题描述】:
经过一周的搜索,我无法编写此查询,请帮助我。 我有 3 张桌子 purchase、selles、stuff。 我想先分别对 purchase.quantity selles.quantity 字段求和,然后减去这两列 purchase.quantity sells.quantity 然后按购买分组.scale, stuff.name
我有这3张桌子
table purchase:
'id', 'invoice_id', 'stuff_id', 'quantity', 'scale', 'price'
table selles:
'id', 'selles_invoice_num', 'stuff_id', 'quantity', 'scale', 'price'
table stuff:
'id', 'name'
我有这个查询,但结果(数量)是错误的
SELECT sum(purchase.quantity) - sum(selles.quantity) as quantities,
purchase.scale,
stuff.name ,
stuff.id
FROM purchase,
selles,
stuff
where purchase.stuff_id = selles.stuff_id
and purchase.scale = selles.scale
and purchase.stuff_id = stuff.id
group by purchase.scale,
stuff.name
ORDER BY stuff.name ,
purchase.scale
【问题讨论】:
-
“结果(数量)错误”是什么意思?
-
添加一些样本数据(不要太多也不要太少),当前结果和预期结果。
-
一般 GROUP BY 规则说:“如果指定了 GROUP BY 子句,则 SELECT 列表中的每个列引用必须标识一个分组列或作为集合函数的参数。” (旧的 MySQL 不关心这个,但可能会返回一个不可预测的结果。新的 MySQL 版本更严格。)
-
请查看我从所有三个表中上传的屏幕截图,分别是购买、销售、东西
-
请看更新(表格数据)