开发者

Django: How do I explicitly make a query with a HAVING clause?

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开发者_JS百科=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.


Does the SQL even work? The having MAX(approve_dt) part certainly looks suspicious. Perhaps you mean this:

SELECT DISTINCT
    main_approve.approve_firm_id,
    main_approve.approve_dt,
    main_approve.approve_result
FROM
    main_approve
    JOIN (
        SELECT 
            approve_firm_id,
            MAX(approve_dt) AS max_dt
        FROM
            main_approve
        GROUP BY 
            approve_firm_id
    ) AS t
    ON
        main_approve.approve_firm_id = t.approve_firm_id
        AND main_approve.approve_dt = t.max_dt
WHERE
    main_approve.approve_result = 0;

It will be easier to construct the ORM expression after you know what exactly is the SQL going to be.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜