I have two tables: authorizations and settlements. 'Settlements' contains a forign key reference to authorizations.
A settlement can also have a status (ERROR, ACCEPTED, etc).
Given this data:
Authorizations Settlements id id | auth_id | status ----- --------------------------- 1 1 1 ERROR 2 2 1 ACCEPTED
I'm trying to write a SQL query to find all authorizations that don't have an ACCEPTED settlement record. I've tried a LEFT OUTER JOIN, but it returns too many rows. For example:
SELECT * FROM authorizations a
LEFT OUTER JOIN settlements s ON a.id = s.auth_id
WHERE s.status is null OR s.status != 'ACCEPTED'
The problem with this is that it will still return an authorization record if it has more than one settlement record, and one of those is ACCEPTED. Or, if there is more than one ERROR record, the authorization will be returned twice.
How can I only fetch single authorization records that don't have a corresponding settlement record with a status of "ACCEPTED"? Is it possible with straight SQL, or will I have to filter the results in my code?