views:

46

answers:

1

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.

A: 

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.

sayap
It does! Moreover it runs the way i want. Say we have row1 [ approve_firm_id = 1 approve_result = 1 approve_dt = today ] and row2 [ approve_firm_id=1 approve_result = 0 approve_dt = yesterday ]My (and your) sql run correct - there is no approve_firm_id=1, because today's approve = 1Another one generated by Django sorts __before__ and returns row with approve_firm_id=1
Vlad Bokov
That SQL definitely doesn't work in PostgreSQL. What database server are you using? MySQL?Anyway, since the HAVING clause should only accept boolean expression, even if the SQL does work in your database server, I don't think it is possible for Django ORM to generate the same SQL. Have you tried rewriting the ORM expression based on the SQL I posted instead?
sayap