Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql SQL查询首先从索引中选择_Mysql_Select_Indexing - Fatal编程技术网

Mysql SQL查询首先从索引中选择

Mysql SQL查询首先从索引中选择,mysql,select,indexing,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的入口行,从该点向下查找下一行中的第一行,如果A为入口A值+10或更大,或-10或更大,则出口行中的B值无关紧要。如果退出是+10或-10,则返回入口指数、退出指数和一些指标将非常好,如

我正在寻找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的入口行,从该点向下查找下一行中的第一行,如果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

使用子查询的快速尝试:-

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

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

SELECT entryindex, exitindex, IF(entryA < exitA, '+10', '-10')
FROM (
  SELECT t1.`index` AS entryindex,
         (SELECT t2.`index` 
          FROM mytable AS t2
          WHERE t2.`index` > t1.`index` AND 
                ((t2.`A` >= t1.`A` + 10) OR (t2.`A` <= t1.`A` - 10))
          ORDER BY `index` LIMIT 1) AS exitindex,
          t1.`A` AS entryA,
         (SELECT t2.`A` 
          FROM mytable AS t2
          WHERE t2.`index` > t1.`index` AND 
                ((t2.`A` >= t1.`A` + 10) OR (t2.`A` <= t1.`A` - 10))
          ORDER BY `index` LIMIT 1) AS exitA        
  FROM mytable AS t1
  WHERE t1.`B` = 1) AS t 
ORDER BY entryindex

我认为最后一行的预期结果是错误的。是的,更正了,谢谢