简体   繁体   English

根据另一个表中的值过滤mysql表

[英]Filter mysql table based on values from another table

I have 2 tables here, STOCK (ID, CODE) and SALES (ID, CODE, STATUS) .我这里有 2 个表, STOCK (ID, CODE)SALES (ID, CODE, STATUS) I want to filter the values of STOCK table by using certain condition from SALES table.我想通过使用 SALES 表中的某些条件来过滤 STOCK 表的值。

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.应从结果中删除状态为 SOLD 和 ASSIGNED 的项目。 Items with Status RETURNED, in SALES table and items which are not yet used from STOCK table should be available for entry. SALES 表中状态为 RETURNED 的项目和 STOCK 表中尚未使用的项目应可用于输入。

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.我尝试了以下代码,但问题是,一旦将已退货商品重新输入到 SALES 表中,并显示 Status SoldAssigned ,它仍然会进入结果。

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.请帮我解决这个问题。

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.请使用给定的示例数据找到相同的LIVE DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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