Select a row in mysql depending on a value of a field in neighbor row

时间:2016-04-04 17:05:00

标签: mysql mysqli

I need to be able to select a row based on a value of the previous row. Given the table:

id      value
---      ---
1        D
2        D
3        N
4        P
5        P
6        P

I want only to select row with ID 4 because the row with ID = 3 had value "N"

So I need to do smth like:

SELECT
 id as current_id,
 value
FROM
 table
WHERE
 (SELECT id FROM table WHERE "current_id" - 1) = "N"

2 个答案:

答案 0 :(得分:1)

try this:

SELECT id AS current_id
, value
FROM table
WHERE id IN (SELECT id + 1 FROM table WHERE value = "N") 

Edit:
Hire is also simple way with non contiguous ID's:

SELECT current_id, value
FROM (SELECT value
  , @old_id AS old_id
  , @old_id := id AS current_id
  FROM table, (SELECT @old_id := 0) AS v
  ORDER BY current_id) AS sq
WHERE exists (SELECT id FROM table AS o WHERE o.value = "N" AND o.id = sq.old_id) ;

答案 1 :(得分:1)

This is a bit elaborate but it works

SELECT o.id,o.value
FROM
(SELECT @rank:=@rank+1 AS rank, id,value,
 CASE WHEN value='N' THEN @rank+1 ELSE 0 END as desiredId
  FROM orders,(SELECT @rank:=0)x 
ORDER BY id ASC)y
JOIN orders o ON
o.id=y.desiredId

FIDDLE