根据条件选择一行

时间:2018-11-12 13:12:07

标签: mysql sql

这是我的MySQL表的一部分:

<style>
.elements-i-want-to-change {
  background-color: [the colour];
  -webkit-print-color-adjust: exact;
}
</style>

我想根据很多条件以及下一行是否包含 | id | opentrap | openrect | lampgroen | lamprood | closeout | openout | limitswitchclose | limitswitchopen | traploop | photocells | rectloop | DateTime | milliseconds | | 92 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 2018-11-09 13:56:41 | 654 | | 93 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 2018-11-09 13:56:42 | 262 | | 94 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 2018-11-09 13:56:42 | 561 | | 95 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2018-11-09 13:56:45 | 83 | | 96 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 2018-11-09 13:56:46 | 189 | | 97 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 2018-11-09 13:56:47 | 402 | | 98 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 2018-11-09 13:56:48 | 611 | | 99 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 2018-11-09 13:56:48 | 916 | traploop = 1

我要使用的查询如下所示(但我不知道如何为下一行写条件):

rectloop = 1

这应该给我:

SELECT * 
FROM table 
WHERE closeout = 0 
    AND openout = 0 
    AND lampgroen = 1 
    AND lamprood = 1 
    AND limitswitchopen = 1 
    AND NEXTROW: traploop = 1 
    OR rectloop = 1;

5 个答案:

答案 0 :(得分:2)

这是使用相关子查询的一种方法:

SELECT *
FROM yourTable t1
WHERE closeout = 0 AND openout = 0 AND lampgroen = 1 AND lamprood = 1 AND
    limitswitchopen = 1 AND
    ((SELECT t2.traploop FROM yourTable t2
     WHERE t2.id > t1.id ORDER BY t2.id LIMIT 1) = 1 OR
    (SELECT t2.rectloop FROM yourTable t2
     WHERE t2.id > t1.id ORDER BY t2.id LIMIT 1) = 1);

Demo

此方法对于id值可能不连续的可能性是很可靠的。对“下一个”行的唯一要求是它具有当前行中倒数第二高的id值。

答案 1 :(得分:1)

您可以使用join来获取“下一个”行-假设“下一个”基于id并且没有空格:

select . . . 
from t join
     tnext
     on tnext.id = t.id + 1
where . . .;

然后可以将条件应用于ttnext

在MySQL 8+中,lead()是更好的选择。

答案 2 :(得分:1)

一个简单的查询,它使用相关的子查询,但是如果id带有空格,则可以使用以下查询:

SELECT *
FROM t AS curr
WHERE closeout = 0 AND openout = 0 AND lampgroen = 1 AND lamprood = 1 AND limitswitchopen = 1
AND 1 = (
    SELECT CASE WHEN traploop = 1 OR rectloop = 1 THEN 1 END
    FROM t AS next
    WHERE id > curr.id
    ORDER BY id
    LIMIT 1
)

Demo on DB Fiddle

答案 3 :(得分:1)

您可以尝试使用Correlated Subquery with Exists()

SELECT t1.* 
FROM table AS t1
WHERE t1.closeout = 0 AND 
      t1.openout = 0 AND 
      t1.lampgroen = 1 AND 
      t1.lamprood = 1 AND 
      t1.limitswitchopen = 1 AND 
      EXISTS (SELECT 1 
              FROM table AS t2 
              WHERE t2.id = t1.id + 1 AND 
                    (t2.traploop = 1 OR t2.rectloop = 1)
             )

PS:这假设id列中没有空格

答案 4 :(得分:1)

这就是您需要的:

SELECT t0.*
FROM
  table t0
  INNER JOIN
  table t1
  ON t0.id + 1 = t1.id
WHERE
  t0.closeout = 0 AND
  t0.openout = 0 AND
  t0.lampgroen = 1 AND
  t0.lamprood = 1 AND
  t0.limitswitchopen = 1 AND
  (t1.traploop = 1 OR t1.rectloop = 1);