我尝试在查询的WHERE子句中使用子查询的结果。我想要使用的属性是last_contact。见下文。
SELECT forename, surname, type,
( SELECT MAX(completed_date)
FROM tblTasks
WHERE prospect_id = tblProspects.prospect_id AND completed = '1'
) AS last_contact,
created_at
FROM tblProspects
WHERE hidden != '1' AND type='Prospect' AND last_contact > DATE_ADD(CURDATE(), INTERVAL -90 DAY)
ORDER BY last_contact ASC
我收到SQL错误:#1054 - 'where子句'中的未知列'last_contact'
非常感谢任何帮助。
感谢。
答案 0 :(得分:2)
你需要使用HAVING
子句来通过自定义别名coulmn来优化你的结果,它们不能在where子句中使用
SELECT
forename,
surname,
type,
(SELECT MAX(completed_date) FROM tblTasks WHERE prospect_id = tblProspects.prospect_id AND completed = '1') AS last_contact,
created_at
FROM tblProspects
WHERE hidden != '1' AND type='Prospect'
HAVING (
last_contact > DATE_ADD(CURDATE(), INTERVAL -90 DAY)
OR last_contact IS NULL
)
ORDER BY last_contact ASC