简体   繁体   中英

SQLite - How to select records from one table that are not in another table

I have a database with 3 tables; tblCustomers, tblBookings, tblFlights.

I want to find the customer's last name (LName), from the Customers table where the customers do not appear in the bookings table. It should return just three names, but it returns the names 10 times each. There are 10 records in the bookings table, so I think the command is returning the correct names, but not once...

I have tried:

SELECT tblCustomers.LName
FROM tblCustomers, tblBookings
WHERE tblCustomers.CustID 
NOT IN (SELECT CustID FROM tblBookings)

How do I return just one instance of the name, not the name repeated 10 times?

The (implicit) cross join on The bookings table in the outer query makes no sense - and it multiplies the customer rows.

Also, I would recommend not exists for filtering instead of not in : it usually performs better - with the right index in place, and it is null -safe:

SELECT c.LName 
FROM tblCustomers c
WHERE NOT EXISTS (SELECT 1 FROM tblBookings b WHERE b.CustID = c.CustID)

For performance, make sure to have an index on tblBookings(CustID) - if you have a proper foreign key declared, it should already be there.

You are doing a CROSS JOIN of the 2 tables.
Use only NOT IN:

SELECT LName 
FROM tblCustomers 
WHERE CustID NOT IN (SELECT CustID FROM tblBookings)

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