Waeez
Waeez

Reputation: 339

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

Upvotes: 0

Views: 56

Answers (1)

pkgajulapalli
pkgajulapalli

Reputation: 1126

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'

Upvotes: 1

Related Questions