Django:如何使用 HAVING 子句显式进行查询?
我需要执行一些如下所示的 SQL:
select approve_firm_id,approve_dt,approve_result
from main_approve
group by approve_firm_id
having MAX(approve_dt) and approve_result=0;
它运行 (mysql-5.1), 但如果我在 Django 模型中尝试像这样:
Approve.objects.annotate(max_dt=Max('approve_dt')).
filter(max_dt__gt=0).filter(approve_result=0).query
生成的查询是这样的:
SELECT `main_approve`.`id`, `main_approve`.`approve_result`,
`main_approve`.`approve_dt`, `main_approve`.`approve_user_id`,
`main_approve`.`approve_firm_id`, `main_approve`.`exported_at`,
MAX(`main_approve`.`approve_dt`) AS `max_dt` FROM `main_approve`
WHERE (`main_approve`.`approve_result` = 0 )
GROUP BY `main_approve`.`id`
HAVING MAX(`main_approve`.`approve_dt`) > 0
ORDER BY NULL
我需要 WHERE 子句位于 GROUP BY 子句之后。
I need to execute some SQL that looks like this:
select approve_firm_id,approve_dt,approve_result
from main_approve
group by approve_firm_id
having MAX(approve_dt) and approve_result=0;
it runs (mysql-5.1),
but if I try in the Django model like this:
Approve.objects.annotate(max_dt=Max('approve_dt')).
filter(max_dt__gt=0).filter(approve_result=0).query
The query generated is this:
SELECT `main_approve`.`id`, `main_approve`.`approve_result`,
`main_approve`.`approve_dt`, `main_approve`.`approve_user_id`,
`main_approve`.`approve_firm_id`, `main_approve`.`exported_at`,
MAX(`main_approve`.`approve_dt`) AS `max_dt` FROM `main_approve`
WHERE (`main_approve`.`approve_result` = 0 )
GROUP BY `main_approve`.`id`
HAVING MAX(`main_approve`.`approve_dt`) > 0
ORDER BY NULL
I need the WHERE clause to be AFTER the GROUP BY clause.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SQL 还能工作吗?
having MAX(approve_dt)
部分看起来确实很可疑。也许您的意思是这样的:在您知道 SQL 到底是什么之后,构造 ORM 表达式会更容易。
Does the SQL even work? The
having MAX(approve_dt)
part certainly looks suspicious. Perhaps you mean this:It will be easier to construct the ORM expression after you know what exactly is the SQL going to be.