0
我有一個大的選擇語句,可以找出聯繫人當前的左側設備和右側設備。它工作正常。大選也會返回該人的contact_id。MySQL JOIN:如何
這...
SELECT locations.name AS location_name, CONCAT_WS(' ', contacts.first_name, contacts.last_name) AS contact_name, contacts.street_1, contacts.street_2, contacts.city, contacts.state, contacts.zip, contacts.home_phone, contacts.cell_phone, contacts.email, sel.side, delivery_date AS delivered_date, CONCAT_WS(': ', makes.name, models.name) AS details, sel.serial_number, contacts.warranty_expiration_email, contacts.warranty_expiration_letter, contacts.upgrade_letter, contacts.email_newsletter, contacts.mail_newsletter
FROM
(SELECT 'Left Device' AS side, left_sn AS serial_number, contact_id, left_make_id AS make_id, left_model_id AS model_id, MAX(left_delivery_date) AS delivery_date
FROM
invoice_hearing_aids
WHERE left_delivery_date IS NOT NULL AND left_return_date IS NULL AND trial_complete = 'Y' AND left_price IS NOT NULL AND company_id = '1' AND left_delivery_date = (SELECT MAX(t2.left_delivery_date)FROM invoice_hearing_aids t2 WHERE t2.contact_id = invoice_hearing_aids.contact_id)
GROUP BY contact_id
UNION
SELECT 'Right Device' AS side, right_sn AS serial_number, contact_id, right_make_id AS make_id, right_model_id AS model_id, MAX(right_delivery_date) AS delivery_date
FROM
invoice_hearing_aids
WHERE right_delivery_date IS NOT NULL AND right_return_date IS NULL AND trial_complete = 'Y' AND right_price IS NOT NULL AND company_id = '1' AND right_delivery_date = (SELECT MAX(t2.right_delivery_date)FROM invoice_hearing_aids t2 WHERE t2.contact_id = invoice_hearing_aids.contact_id)
GROUP BY contact_id
) sel
LEFT JOIN hearing_aid_models models ON models.id = sel.model_id
LEFT JOIN hearing_aid_makes makes ON makes.id = sel.make_id
LEFT JOIN contacts ON contacts.id = sel.contact_id
LEFT JOIN locations ON locations.id = contacts.location_id
我要添加信息的一行。我想返回具有聯繫人的最後約會日期的列。
約會表具有start_date和一個名爲post_appt_status_id的列。我想返回MAX(start_date)WHERE post_appt_status_id IN(6,7)。
如果約會表中沒有約會,則返回NULL。
我嘗試添加這結尾:
LEFT JOIN appointments appt ON appt.contact_id = sel.contact_id
WHERE appt.post_appt_status_id IN (6,7)
,我addded這開始選擇頂部:
MAX(appt.start_date)
但它沒有返回的所有記錄。事實上,我只得到1行,我應該得到1972行,這是我添加我的appts JOIN之前得到的。
謝謝。我剛剛嘗試過。我只有920條記錄。 –
是不是要減少到最近的約會?我假設這些contact_id行中有很多是用於多個約會的,對吧? – natecornell