I'm trying to select records from 3 tables using a JOIN which is working well but I now need to add some additional conditions to the SELECT which I can't figure out. My current select works like this:
SELECT user.*, address.*, state.* FROM user
LEFT JOIN address ON user.id = address.user_id
LEFT JOIN state ON user.id = state.user_id
Now, the address and state could have multiple records but both tables have a bit field to indicate that they are the primary record and that's the one I want to select. I have tried adding a WHERE address.state = b'1'
to the statement but it only returns those records that have a primary record, what I would ideally like to do is select the top record from the address/state table sorted by the primary field so the primary will be selected if it exists but the next record will be selected if there is no primary.
How can I achieve this with MySQL 5?