Mysql 子查询中的问题

Mysql issue in subquery

我有两个 mysql table 名为 itemstock.

select * From stock;
+----------+----------+-------+---------+-------------------+---------------+
| stock_id | qty_type | qty   | item_id | stock_location_id | stock_type_id |
+----------+----------+-------+---------+-------------------+---------------+
|       48 | v        | 44.00 |       1 |                 1 |             1 |
|       49 | v        |  8.00 |     263 |                 1 |             1 |
|       50 | a        |  6.00 |       1 |                 1 |             1 |
|       51 | a        |  4.00 |     263 |                 1 |             1 |
|       56 | a        | 21.00 |       1 |                 1 |             1 |
|       57 | a        | 57.00 |     263 |                 1 |             1 |
|       58 | a        |  6.00 |     264 |                 1 |             1 |
|       59 | a        | 19.00 |     301 |                 1 |             1 |
+----------+----------+-------+---------+-------------------+---------------+

现在我想获取 item table 中的所有商品以及所有可用的 qty 库存 table。

我就是这样试的。但我无法从库存中获得正确的数量 table。

SELECT i.item_id
     , i.item_name
     , i.item_code
     , i.sku
     , i.min_qty 
     , i.max_qty   
     , sum(current_stock) as stock
  FROM item i 
      LEFT JOIN (
         SELECT item_id, qty_type, COALESCE(SUM(qty),0) AS current_stock 
           FROM stock 
       GROUP BY item_id
                ) s USING(item_id)
  WHERE s.qty_type = 'a';

上述查询的结果

+---------+------------------+-----------+------------+---------+---------+-------+
| item_id | item_name        | item_code | sku        | min_qty | max_qty | stock |
+---------+------------------+-----------+------------+---------+---------+-------+
|     264 | HONE CLIP RUBER  | MM-00264  | NOOR-00264 |      10 |      20 | 25.00 |
+---------+------------------+-----------+------------+---------+---------+-------+
1 row in set (0.001 sec)

你看,我无法获取所有商品记录,而且我的查询结果也有错误。

我能知道我在查询中做错了什么吗?

请试试这个:

SELECT i.item_id
     , i.item_name
     , i.item_code
     , i.sku
     , i.min_qty 
     , i.max_qty   
     , current_stock as stock
FROM item i 
LEFT JOIN
    (
        SELECT item_id, SUM(qty) AS current_stock 
        FROM stock 
        WHERE qty_type = 'a'
        GROUP BY item_id
                
    ) s USING(item_id);

将条件 qty_type = 'a' 移到子查询中,并在主查询中使用 COALESCE(),这样对于与连接不匹配的项目,您会得到 0:

SELECT i.*,   
       COALESCE(s.current_stock, 0) AS stock
FROM item i 
LEFT JOIN (
  SELECT item_id, SUM(qty) AS current_stock 
  FROM stock
  WHERE qty_type = 'a' 
  GROUP BY item_id
) s USING(item_id);

只在子查询中需要聚合。