Vishnu Vishnu - 2 months ago 7
MySQL Question

Filter mysql table based on values from another table

I have 2 tables here,

STOCK (ID, CODE)
and
SALES (ID, CODE, STATUS)
. I want to filter the values of STOCK table by using certain condition from SALES table.

For an example, if we have these values in

STOCK Table:

A1
A2
A3
A4
A5


and in

SALES Table:

A1 - Sold
A2 - Returned
A3 - Assigned
A2 - Sold
A4 - Returned


The result should be:

A4
A5


Which ever items with status SOLD and ASSIGNED should be removed from result. Items with Status RETURNED, in SALES table and items which are not yet used from STOCK table should be available for entry.

I tried the following code but the problem is that, once a RETURNED item is re-entered in SALES table with Status Sold or Assigned, it is still getting in to the result.

SELECT t1.CODE
FROM STOCK t1
LEFT JOIN SALES t2 ON t2.CODE = t1.CODE
WHERE (t2.CODE IS NULL OR (t2.STATUS <> 'Sold' AND t2.STATUS <> 'Assigned'));


Please help me solve this issue.

Answer

Based on your condition the following query return your expected result:

SELECT S1.CODE
FROM STOCK S1
LEFT JOIN (  
        SELECT t1.CODE
        FROM STOCK t1
        JOIN SALES t2 ON t2.CODE = t1.CODE
        WHERE t2.STATUS IN ('Sold', 'Assigned')) S2 ON S2.CODE = S1.CODE
WHERE S2.CODE IS NULL;

Please find the LIVE DEMO for the same with the given sample data.

Comments