LEFT JOIN MYSQL

0

I have 3 tables from which I am trying to collect data by doing LEFT JOINS.

In the contacts table I have 2 types of contacts, people and companies each with their unique id and another associative one.

When I execute the query that I leave below it collects me and organizes the data more or less well but I associate everything inside contacts_info with the contacts that correspond to people and I do not know how to include 2 times of the same table.

To explain myself better: I need to select contacts_info.phone_number and associate it with person.phone_number and company.phone_number

SELECT
tasks.id,
tasks.id_type,
tasks.id_account,
tasks.id_contact,
tasks.id_contact_company,
tasks.id_user
tasks.date_added,
tasks.date_modified,
tasks.title,


contacts.id AS contact_id,
contacts.name,
contacts.job,
contacts.company,

contacts_info.address,
contacts_info.city,
contacts_info.state,
contacts_info.zipcode,
contacts_info.country_static_name,
contacts_info.email,
contacts_info.phone_number,
contacts_info.website

FROM
tasks

LEFT JOIN contacts
ON contacts.id = tasks.id_contact

LEFT JOIN contacts_info
ON contacts.id = contacts_info.id_contact

WHERE tasks.deleted = 0
    
asked by Infobuscador 21.03.2017 в 10:16
source

1 answer

0

If the field company of the table contacts is an ID of the company, and corresponds to a row of the table contact_info then you simply do an LEFT JOIN additional with the table contact_info

SELECT tasks.*,
       contacts.id AS contact_id,
       contacts.name,
       contacts.job,
       contacts.company,
       contact_person.phone_number
       contact_company.phone_number

FROM
tasks

LEFT JOIN contacts ON contacts.id = tasks.id_contact

LEFT JOIN contacts_info contact_person
       ON contacts.id = contact_person.id_contact

LEFT JOIN contacts_info contact_company  
       ON contacts.company = contact_company.id_contact

WHERE tasks.deleted = 0

If there is a field company_id in your table contacts then you have to replace that field with the one I used in the absence of more information.

    
answered by 21.03.2017 в 11:50