I’m trying to write an SQL statement to retrieve a list of users from a database, along side their company name (if they have a company associated with them). However, there are a couple gotchas:
- Not all users have companies, but I still need to show these people in the list.
- Even if a user has a company, that company could be soft-deleted (the record is still in the database, but is flagged with is_deleted = 1), and I don’t want to show users that are associated with “deleted” companies.
So essentially I want to SELECT from the User table and LEFT JOIN the company table, but I don’t want to include the User record at all if the company they are assigned to is_deleted.
My first inclination is that I would have to use a UNION to merge two queries together, but I was hoping there would be a cleaner way to do it?
Using Mysql 5.1
C.id IS NULL gets the users with no company, and C.is_deleted = 0 gets the users with companies that haven’t been soft-deleted.