SQL查询首先从索引中选择

时间:2016-02-08 12:13:48

标签: mysql select indexing

我正在寻找一个SQL查询来查找以下内容:

index A   B
 1    5   1
 2    10  1
 3    15  0
 4    10  0
 5    20  1
 6    5   0
 7    15  1
 8    25  0
 9    20  0
 10   15  0

选择B为1的“entry”行,从该点向下查找第一行的下一行,“exit”行,其中A是条目A值+10以上,或者-10以上,不是重要的是“退出”行中B的值。返回入口索引,退出索引和一些指标,如果退出是+10或-10将是伟大的,如果不可能,nwm。所以在这种情况下,查询的输出应该是

entryindex exitindex +10/-10
1 3 +10    //entry in line 1, because B is 1, exit on line 15, because 15 is 5 +10
2 5 +10
5 6 -10
7 8 -10

2 个答案:

答案 0 :(得分:0)

使用子查询快速尝试: -

SELECT t1.index AS entryindex,
        t2.index AS exitindex,
        IF(t1.A <= t2.A, '+10', '-10') AS '+10/-10'
FROM
(
    SELECT t1.index AS t1_index,
            MIN(t2.index) AS t2_index
    FROM a_table t1
    INNER JOIN a_table t2
    ON t1.index < t2.index
    AND (t1.A <= t2.A - 10
    OR t1.A >= t2.A - 10)
    WHERE t1.B = 1
    GROUP BY t2.index
) sub0
INNER JOIN a_table t1
ON t1.index = sub0.t1_index
INNER JOIN a_table t2
ON t2.index = sub0.t2_index

答案 1 :(得分:0)

您可以使用相关子查询来获得预期结果:

Template.storageRequest.onCreated(function () {

// Use this.subscribe inside onCreated callback

var GET = {};
var query = window.location.search.substring(1).split("&");
for (var i = 0, max = query.length; i < max; i++)
{
    if (query[i] === "") // check for trailing & with no param
        continue;

    var param = query[i].split("=");
    GET[decodeURIComponent(param[0])] = decodeURIComponent(param[1] || "");
}

Template.storageRequest.requestData = GET;


});

Demo here