我有三张桌子:
ITEMS
+----+--------------------------+----------+
| id | nome | quantity |
+----+--------------------------+----------+
| 1 | Pantaloni beige | 10 |
| 2 | Camicia cotone e seta | 1 |
| 3 | Camicia da notte | 5 |
| 4 | Completo notte | 3 |
+----+--------------------------+----------+
TRANSACTIONS
+----+---------------------+----------+-------------+
| id | data | quantity | id_articolo |
+----+---------------------+----------+-------------+
| 1 | 2016-07-19 15:28:09 | 3 | 1 |
| 2 | 2016-07-19 15:29:50 | 1 | 1 |
| 3 | 2016-07-19 15:59:34 | 1 | 2 |
| 4 | 2016-07-19 16:00:59 | 1 | 3 |
| 5 | 2016-07-19 16:01:10 | 1 | 188 |
| 6 | 2016-07-19 16:11:15 | 1 | 193 |
| 7 | 2016-07-19 16:11:24 | 1 | 194 |
| 8 | 2016-07-19 16:11:55 | 1 | 195 |
| 9 | 2016-07-19 16:51:14 | 1 | 204 |
+----+---------------------+----------+-------------+
RETURNED_ITEMS
+----+---------+-------------+----------+
| id | id_reso | id_articolo | quantity |
+----+---------+-------------+----------+
| 1 | 54 | 1 | 6 |
| 2 | 54 | 3 | 1 |
| 3 | 54 | 392 | 1 |
| 4 | 54 | 398 | 1 |
+----+---------+-------------+----------+
加入" transactions.id_articolo" =" returned_items.id_articolo" =" items.id"
我想检索一个完整列表,其中只包含
中的可用产品(items.quantity) - (transactions.quantity) - (returned_items.quantity)> 0
例如。在上面的数据
有什么想法吗? 非常感谢! V.
答案 0 :(得分:0)
看起来您需要使用内联视图来汇总quantity
表格和transactions
表格中的returned items
SELECT i.id
, i.quantity
, IFNULL(t.quantity,0) AS t_quantity
, IFNULL(r.quantity,0) AS r_quantity
, i.quantity - IFNULL(t.quantity,0) + IFNULL(r.quantity,0) AS calc_qty
FROM items i
LEFT
JOIN ( SELECT tt.id_articolo
, SUM(tt.quantity) AS quantity
FROM transactions tt
GROUP BY tt.id_articolo
) t
ON t.id_articolo = i.id
LEFT
JOIN ( SELECT rr.id_articolo
, SUM(rr.quantity) AS quantity
FROM returned_items rr
GROUP BY rr.id_articolo
) r
ON r.id_articolo = i.id
HAVING calc_qty > 0
ORDER BY i.id
进行测试时,请省略HAVING
子句。
请注意,上述查询中calc_qty
的表达式包含一个加法运算。继续将数值与您需要的任何算术运算相结合。来吧,做一个减法就是满足要求。