Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi Table NOT EQUAL in Access Query

I have two tables. VEHICLES and OWNERSHIP. I am trying to make a query that will give me a list of all VEHICLES NOT in the OWNERSHIP table. I basically need a report of my available VEHICLE inventory. I tried this query:

SELECT VEHICLE.*
FROM VEHICLE, OWNERSHIP
WHERE (VEHICLE.VEH_ID <> OWNERSHIP.VEH_ID);

Im getting:enter image description here

When I do an equal I get all vehicles which are listed in the ownership so that works. But the NOT Equal does not. Any ideas?

like image 435
Batman Avatar asked Aug 25 '26 15:08

Batman


2 Answers

Try

SELECT VEHICLE.*
FROM VEHICLE
WHERE NOT EXISTS
(SELECT NULL FROM OWNERSHIP WHERE VEHICLE.VEH_ID= OWNERSHIP.VEH_ID);
like image 88
a1ex07 Avatar answered Aug 28 '26 04:08

a1ex07


The NOT EXISTS approach can be slow if your tables contain many rows. An alternative approach which can be much faster is to use a LEFT JOIN with a WHERE clause to return only the rows where the right-hand join field is Null.

SELECT VEHICLE.*
FROM
    VEHICLE AS v
    LEFT JOIN OWNERSHIP AS o
    ON v.VEH_ID = o.VEH_ID 
WHERE o.VEH_ID Is Null;

You could use Access' "Find Unmatched Query Wizard" to create a similar query.

If both tables are small you probably won't notice a difference. But it should be easy to check whether the difference is noticeable. And this approach will serve you better if your tables grow substantially over time.

like image 29
HansUp Avatar answered Aug 28 '26 04:08

HansUp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!