我正在尝试从storage_movements
表中获取所有记录,直到weight
列总和达到特定值。这是我正在尝试的查询:
SELECT id, storage_id, weight, (@total := weight + @total) as c_sum
FROM `storage_movements`
JOIN (SELECT @total := 0) r
WHERE @total < 100000
AND weight > 0
AND storage_id=4
AND id < 1000
ORDER BY id DESC
它不起作用。它继续添加@total
而不尊重WHERE
子句(@total
超过100000
,直到所有记录都完成为止。)
如果我做出一些改变,就会发生奇怪的事情。像:
AND id < 1000
行,它会像预期的那样工作(但我需要这一行)。 ORDER BY id DESC
行,也可以使用(但我也需要这一行)。AND storage_id=4
,它会有效(但我也需要这一行)。AND storage_id=4
更改为AND storage_id < 4
,它会有效(为什么,上帝?)。有人可以告诉我为什么会这样,或者告诉我如何做我想做的事情?
答案 0 :(得分:2)
在最新版本的MySQL中,您需要先排序:
SELECT id, storage_id, weight, (@total := weight + @total) as c_sum
FROM (SELECT sm.*
FROM storage_movements sm
WHERE weight > 0 AND storage_id = 4 AND id < 1000
ORDER BY id
) sm CROSS JOIN
(SELECT @total := 0) r
WHERE @total < 100000;
我对@total
中使用WHERE
感到不满。我想我会选择:
SELECT id, storage_id, weight, (@total := weight + @total) as c_sum
FROM (SELECT sm.*
FROM storage_movements sm
WHERE weight > 0 AND storage_id = 4 AND id < 1000
ORDER BY id
) sm CROSS JOIN
(SELECT @total := 0) r
HAVING c_sum < 100000;