I am trying to setup a simple database in which I have a user and store both their residential and postal address. I have 2 tables
Users
id (Primary Key)
name (Varchar 255)
residential_id (foreign key)
postal_id (foreign key)
Address
id (primary key)
type (enum of R and P)
street (varchar 255)
suburb (varchar 255)
I am tring to do an inner join so I end up with a result-set that looks like.
id – name – residential_street – residential_suburb, postal_street, postal_suburb
I keep getting null results for the address details, I assume this is because I am getting two sets of data from the address table and there is a conflict. Is it possible to return the address fields linked to the residential ID and the postal ID at the same time?
My SQL syntax is
SELECT * FROM users
LEFT JOIN address
ON (users.residential_id = address.id AND users.postal_id = address.id)
EDIT. As has been pointed out my DB design is rather poor and I am looking to improve it.
The key thing I am trying to achieve is that I can store the details of a person along with their associated residential and postal address. I will never be looking to expand the database to include a work address for example so hopefully that cuts down the complexity of the table.
The following assumes that
What you want is:
The key here is you have to join to the address table TWICE. The address type discriminator is needed so that each join selects only the appropriate type of address.
If your schema is different, please clarify and I’ll modify my answer.