MySQL - Referencing aggregate column in where clause

大兔子大兔子 提交于 2019-12-23 10:54:14

问题


This seems so simple but I can't seem to figure it out without doing subqueries (which seem to slow down the queries significantly - takes almost 10 seconds instead of <1).

Let's say I have a table of sent documents, and I want to select the ones that have been updated since they've last been sent, and the ones that have never been sent.

SELECT d.document_id, max(sd.document_sent_date) as last_sent_date
FROM documents d
LEFT JOIN sent_documents sd ON d.document_id=sd.document_id
WHERE last_sent_date is NULL OR last_sent_date<d.last_updated
GROUP BY d.document_id

Is something like this possible? Basically, I want to use the result of max() in my where clause.


回答1:


You want the having clause.

General rule: where operates on date before aggregation, having operates on data after aggregation.



来源:https://stackoverflow.com/questions/14638634/mysql-referencing-aggregate-column-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!