简体   繁体   中英

SQL query returns null Mysql

Here is a sql query:

SELECT SUM(a.quantity)-SUM(IF(ISNULL(b.quantity),0,b.quantity)) AS stock 
FROM wp_wpsp_inventory_items a, wp_wpsp_assigned_inventory b 
WHERE a.master_id='9' AND 
     (CASE WHEN ISNULL(b.quantity) 
           THEN '' ELSE a.master_id=b.master_id 
      END)

There are two tables a and b . Table a stores all the inflows and the table b stores all outflows. Here I'm trying to calculate the stock by subtracting outflows from inflows. But there are situations when there is no entry of an Item in Table b is such case the query returns NULL . I tried using IF() and ISNULL() but nothing worked. Please help

You should use left outer join.

SELECT SUM(a.quantity - coalesce(b.quantity, 0)) AS stock
FROM wp_wpsp_inventory_items a 
LEFT JOIN
wp_wpsp_assigned_inventory b
ON a.master_id = b.master_id
WHERE a.master_id = '9'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM