此查询应该为我提供已取消的约会(post_appt_status_id = 3)并且尚未重新预订。
SELECT appointments.id, concat_ws(' ', contacts.first_name, contacts.last_name) AS contact_name, contacts.id, appointments.start AS appt_date
FROM
appointments appts2
LEFT JOIN contacts ON contacts.id = appointments.contact_id
WHERE marketing_event_id ='740' AND appointments.company_id = '1'
AND appointments.post_appt_status_id = '3'
AND contacts.id NOT IN (SELECT contact_id FROM appointments WHERE appointments.start > appt_date)
GROUP BY contacts.id
问题在于子选择。我无法传递appt_date值以使其工作。我得到一个错误,它是一个未知的列。
答案 0 :(得分:1)
正如您所见,您不能使用这样的别名。相反,您可以完全限定列名称并引用外部查询中的表:
SELECT appointments.id,
concat_ws(' ', contacts.first_name, contacts.last_name) AS
contact_name,
contacts.id,
appointments.start AS appt_date
FROM appointments appts2
LEFT JOIN contacts ON contacts.id = appointments.contact_id
WHERE marketing_event_id ='740' AND
appointments.company_id = '1' AND
appointments.post_appt_status_id = '3' AND
contacts.id NOT IN (SELECT contact_id
FROM appointments
WHERE appointments.start > appts2.start -- Here!
)
GROUP BY contacts.id
答案 1 :(得分:1)
您必须使用别名appts2
:
SELECT appointments.id, concat_ws(' ', contacts.first_name, contacts.last_name) AS contact_name, contacts.id, appointments.start AS appt_date
FROM
appointments appts2
LEFT JOIN contacts ON contacts.id = appts2.contact_id
WHERE marketing_event_id ='740' AND appts2.company_id = '1'
AND appts2.post_appt_status_id = '3'
AND contacts.id NOT IN (SELECT contact_id FROM appointments WHERE appointments.start > appts2.appt_date)
GROUP BY contacts.id