假设我有一个返回以下结果的查询:
| val | type | i |
----------------------
| 59 | 1 | 1 |
| 40 | 2 | 2 |
| 12 | 1 | 3 |
| 3 | 2 | 4 |
| 24 | 1 | 5 |
| 30 | 1 | 6 |
| 98 | 2 | 7 |
| 45 | 2 | 8 |
| 46 | 1 | 9 |
val = an arbitrary number
type = 1 or 2
i = auto increment column, just for reference
我想执行以下减法:
A - B
A: Value of row of type '2'
B: Value of row above A of type '1' if it exists, but without crossing a row of type '2'
我真的希望这是有道理的..
一些例子:
Row i=2 is of type 2. So the first row above it of type 1 is i=1.
So the subtraction will be: 40 - 59 = -19
Row i=7 is of type 2. So the first row above it of type 1 is i=6
So the subtraction will be: 98 - 30 = 68
Row i=8 is of type 2. But if we go above we cross a value of type 2.
So the subtraction should return 0, or be ignored, whichever is simplest.
最后,结果应该返回一列 type=1 和减去的 value 的值。
例如:
| val | diff |
--------------
| 59 | -19 |
| 12 | -9 |
| 24 | 0 | ***
| 30 | 68 |
| 46 | 0 | ***
*** Return diff=0 if the subtraction was never made for this row.
我有获取我的初始表的查询。我知道如何做减法(在实际情况下 val 是一个日期,但我在这个例子中保持简单)。
我唯一不知道该怎么做是根据 MySQL 中的不同行执行逻辑。例如,如何根据某些条件找到最近的行,然后引用该行以对其执行某些操作?是否有一种方法可以引用当前的“i”并对(i 处的行)减(i-1 处的行)或类似的东西进行减法。
我已经在这上面花了很多时间,我正要放弃,改用 php 来做,并降低性能。作为最后的手段,我在这里问是否有办法直接在 mysql 中完成所有这些操作?
我不需要完整的解决方案,因为这是非常复杂的要求,但我会接受你能给我的任何建议或指示。我在 MySQL 方面不是最好的,所以也许我错过了一些简单的东西。
谢谢。