简体   繁体   中英

How to extract records which do not met a condition?

Dears,

I am using MS Access and need to figure out the following:

Let's say I have a query with 2 tables (inner join).

Table1: ITEM_ID, ITEM_NAME.

Table2: ITEM_ID, CATEGORY_ID.

Multiple CATEGORY_IDs are assigned to one ITEM_ID.

The data set is really huge; very prone to performance issues.

I would need to extract all ITEM_IDs which have not a specific category ID - say "003" - assigned.

I am not able to use criteria for field CATEGORY_ID Not Like "003" as the data set is so huge and the query would like to extract all the ITEM_ID + ITEM_NAME which have other CATEGORY_ID values (say "001, 002, 004-999") = performance issues.

Is there way to do that? I need to identify materials on stock which are not assigned with category 003.

Please let me know, your help will be highly appreciated.

"n00b alert" Be patient with me pls as I am a true beginner in MS Access queries creation.

Thank you, Petr J.

You would use not exists :

select i.*
from items as i
where not exists (select 1
                  from categories as c
                  where c.item_id = i.item_id and c.category_id = "003"
                 );

For performance, you want an index on categories(item_id, category_id) .

You might want to try a left join :

SELECT t1.ITEM_ID, t1.ITEM_NAME
FROM Table1 AS t1
  LEFT JOIN (SELECT ITEM_ID FROM Table2 WHERE CATEGORY_ID = "003") AS t2
    ON t1.ITEM_ID = t2.ITEM_ID
WHERE t2.ITEM_ID Is Null;

I suggest to create an index on CATEGORY_ID , and, if no referential integrity is in place, also on ITEM_ID (both Table2).

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