I have several tables I need to query in order to get all the rows for a certain user. The tables basically look like this
contact
=======
id_contact PK
firstName
lastName
...
contact_phone
===============
id_contact_phone, PK
id_contact, FK
id_phone_type, FK
phone
...
phone_type
============
id_phone_type PK
phone_type
....
And there's a bunch of tables similar to those except they are for email
, phone
etc. I need to display all that information for a given contact, I'm using several LEFT JOIN
but I'm unsure on how to output the information.
This is my query
SELECT contact.id_contact, contact.lastName, contact.firstName, contact_email.email, email_type.email_type, contact_phone.phone, phone_type.phone_type, contact_company.contact_title, company.company_name
FROM contact
LEFT JOIN contact_email
ON contact.id_contact = contact_email.id_contact
LEFT JOIN email_type
ON contact_email.id_email_type = email_type.id_email_type
LEFT JOIN contact_phone
ON contact.id_contact = contact_phone.id_contact
LEFT JOIN phone_type
ON contact_phone.id_phone_type = phone_type.id_phone_type
LEFT JOIN contact_company
ON contact.id_contact = contact_company.id_contact
LEFT JOIN company
ON contact_company.id_company = company.id_company
WHERE contact.id_contact = $cid
My problem is that if a certain contact has several phone numbers, emails etc. the query will obviously return more than 1 row so I'm not exactly sure how to display the information since most of the columns will be duplicates of each others. Here's an example of what that query might return
+===========================================================================================+
| id_contact | lastName | firstName | email | email_type | phone | phone_type |
+===========================================================================================+
| 1 | Doe | John | [email protected] | Work | 555-1234 | Work |
+------------+----------+-----------+------------------+------------+----------+------------+
| 1 | Doe | John | [email protected] | Work | 555-2222 | Mobile |
+-------------------------------------------------------------------+----------+------------+
| 1 | Doe | John | [email protected] | Personal | 555-1234 | Work |
+------------+----------+-----------+------------------+------------+----------+------------+
| 1 | Doe | John | [email protected] | Personal | 555-2222 | Mobile |
+-------------------------------------------------------------------+----------+------------+
How can I display the information in php without having redundant data and can my query be optimized?