I have following table structure:
Users
- UserId (primary key)
- UserName
SomeItems
- SomeId(FK to Users.UserId)
- SomeItemId (primary key)
- Name
- Other stuff...
SomeOtherItems
- SomeId2 (FK to Users.UserId)
- SomeOtherItemId (primary key)
- Name
- Other stuff...
I want to delete records from Users table which do not exist in SomeItems and SomeOtherItems tables.
I can do this:
DELETE from Users
FROM Users u
WHERE u.UserId NOT IN
(SELECT DISTINCT SomeId FROM SomeItems
UNION
SELECT DISTINCT SomeId2 FROM SomeOtherItems)
However, it is very slow. I assume it executes the UNION query for every record, doesn't it? Is there any way to improve the performance?