I need to combine 3 phone numbers for a user into one row. The end result would look like this
contactId | phone | mobile | fax
my tables look like this with the phone numbers broken into their own rows by phoneTypeId
contact_phone_link
contactId | contactPhoneNumberId
3344 | 1
contact_phone_numbers
id | phoneTypeId | phoneNumber
123 | 1 | 555-555-5555
phone_types
id | phoneTypeName
1 | Phone
2 | Mobile
3 | Fax
Dana thanks for your help, I’m getting closer to understanding this. I see how it’s grouping and naming and then grouping again.
I’ve gone through and adjusted the syntax, but I’m still having problems where it gets to ‘phone_link.phoneTypeId’. I think it’s because ‘contact_phone_link’ doesn’t hold ‘phoneTypeId’. Also it gets hung up when the SELECT section and JOIN section had the same variable name like ‘phone’ so I added a 1.
Tell me if I’m way off.
SELECT
`ct`.`id` AS contact_id,
`phone1`.`lineNumber` AS phone,
`fax1`.`lineNumber` AS fax,
`mobile1`.`lineNumber` AS mobile
FROM `cmd`.`contacts` AS ct
LEFT JOIN `cmd`.`contact_phone_link` AS `phone_link` ON (`phone_link`.`contactId` = `ct`.`id` AND `phone_link`.`phoneTypeId` = 1)
LEFT JOIN `cmd`.`contact_phone_numbers` AS `phone1` ON (`phone`.`id` = `phone_link`.`contactPhoneNumberId`)
LEFT JOIN `cmd`.`contact_phone_link` AS `fax_link` ON (`fax_link`.`contactId` = `ct`.`id` AND `fax_link`.`phoneTypeId` = 2)
LEFT JOIN `cmd`.`contact_phone_numbers` AS `fax1` ON (`fax`.`id` = `fax_link`.`contactPhoneNumberId`)
LEFT JOIN `cmd`.`contact_phone_link` AS `mobile_link` ON (`mobile_link`.`contactId` = `ct`.`id` AND `mobile_link`.`phoneTypeId` = 3)
LEFT JOIN `cmd`.`contact_phone_numbers` AS `mobile1` ON (`mobile`.`id` = `mobile_link`.`contactPhoneNumberId`)
WHERE (`ct`.`id` = 4160);
Edited solution below.
Given your table structure, I think using sub-queries might be required. My solution actually looks a little more like @Eugene’s now, but you want to
left joinagainst aninner join. My sub-queries check the phone type and emit (a) a contact id and (b) a line number.Let me know if this works. I think it should be closer.