是否可以使用在ORDER BY之后更新自身的变量计数器

时间:2012-07-28 07:59:35

标签: mysql sql

我有以下查询,如果我不使用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

有没有办法得到这个?正在计算变量,然后对结果进行排序。有没有办法强制首先排序结果,然后计算变量?

1 个答案:

答案 0 :(得分:3)

您是否尝试过在子查询上移动排序?

e.g。

set @a:=0;

SELECT doc, @a as before, mov, (@a:=@a+mov) as after, date  
FROM
(
    SELECT doc,  movement as mov, 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"
    order by date
) as x