产品'基于存储在两个不同表中的事务的数量计算

时间:2016-10-17 18:17:11

标签: mysql

我有三张桌子:

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

例如。在上面的数据

  • 第1项= 0 [排除]
  • 第2项= 0 [排除]
  • 第3项= 3 [列入清单]
  • 第4项= 3 [包含]

有什么想法吗? 非常感谢! V.

1 个答案:

答案 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的表达式包含一个加法运算。继续将数值与您需要的任何算术运算相结合。来吧,做一个减法就是满足要求。