Skip to content
Advertisement

Join twice table with two foreign keys

I’d like to extract information about people and companies stored in my DB. I have 2 tables (Clients and Contacts) that point to a unique Address table containing 2 foreign keys (addressClientID and addressContactID). Clients can have multiple addresses, Contacts usually one and it’s either a custom address (addressContactID will be pointing to the contact id otherwise NULL) or the address of the Client who’s working for. The query should extract the name of the contact, name of the company the contact is working for and the city. The latter must be the city of the company (if the addressContactID is NULL) or the city of the contact (if addressContactID points to a contact id).

I’ve tried multiple types of joins with no success. The DBMS is MySql 5.2

The expected result is something like

Advertisement

Answer

This is what I came up with:

Note however that your Contact 1 is working for Client1 which has two addresses. So I added the AND a2.addressContactId IS NULL line to only pick an address without assigned addressContactId in this case, but depending on your real data, you might still get duplicates (if you have one contact working for a company with two addresses without addressContactId, for example)

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement