0

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

4
  • A query itself never returns NULL, but an empty result set instead. So what is the real question? Do you ask about how to handle that case in your application? Commented May 9, 2018 at 9:23
  • In the above querying I'm querying quantity for master_id=9 but in some cases, my 2nd Table b has no entry for master_id=9 Commented May 9, 2018 at 9:25
  • Yes, that can be possible. But why is that a real problem? Commented May 9, 2018 at 9:26
  • Surely the other way around is also a possibility? Commented May 9, 2018 at 9:26

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Syntax Error You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'a.master_id = b.master_id WHERE a.master_id = '9' LIMIT 0, 25' at line 5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.