我有以下查询,如果我不使用 ORDER BY 子句,变量 a 效果很好:
设置@a:=0;
SELECT doc, @a as before, movement as mov, (@a:=@a+movement) as after, date
FROM movements m
LEFT JOIN (
SELECT doc, 1 as tdoc, date
FROM invoices
UNION ALL
SELECT doc, 2 as tdoc, date
FROM nulled
) sub
ON m.doc=sub.doc and m.doc_type = sub.tdoc
WHERE m.product_id="XXXX"
所以我得到类似的东西:
DOC BEFORE MOVEMENT AFTER DATE
006 0 10 10 2012-07-01
008 10 -3 7 2012-07-03
015 7 5 12 2012-06-20
但是我希望按日期对运动进行排序,因此我在查询末尾包含了 ORDER BY 日期,我得到:
DOC BEFORE MOVEMENT AFTER DATE
015 7 5 12 2012-06-20
006 0 10 10 2012-07-01
008 10 -3 7 2012-07-03
而不是我想要的:
DOC BEFORE MOVEMENT AFTER DATE
015 0 5 5 2012-06-20
006 5 10 15 2012-07-01
008 15 -3 12 2012-07-03
有没有办法得到这个?正在计算变量,然后对结果进行排序。有没有办法强制先排序结果然后计算变量?