Use MySQL to select the next one record after a matching value

0

How can I select all rows next to the row matching with the condition?

This is the table structure with 10 rows, but the number of rows increase in the future.

Table structure Plain text:

ID      Date        N1
1     DateTime    9  
2     DateTime    2
3     DateTime    5
4     DateTime    9
5     DateTime    3
6     DateTime    6
7     DateTime    7
8     DateTime    9
9     DateTime    3
10    DateTime    9

Note: The "DateTime" string it's just symbolic, it would be any DateTime.

I am trying to know the first N1 number after the number: 9

I tried several ways but the result is not what I need.

The expected result is:

ID      Date        N1
2     DateTime      2
5     DateTime      3
9     DateTime      3

Martini002

Posted 2017-04-10T22:01:51.997

Reputation: 43

Answers

2

You can use a Temp Table to hold the Id of the records where N1 is equal to 9. You then select all the records from the Times table where the Id is what values are in the temp table plus one which is the very next record from the Id column the very next record after the N1 value of 9.

SQL Query

DROP TABLE IF EXISTS t1;
CREATE TEMPORARY TABLE t1 (SELECT id FROM numbers WHERE N1 = 9);
Select * FROM t1;

SELECT * FROM numbers
WHERE id IN (Select id+1 FROM t1);

Or

SELECT * FROM numbers WHERE id IN (SELECT ID+1 FROM numbers WHERE N1 = 9)

Confirmation

Select * from Times

enter image description here

With above query

enter image description here


Further Resources

Pimp Juice IT

Posted 2017-04-10T22:01:51.997

Reputation: 29 425

Not working for me, it shows IDs(1,4,8,10) Where the N1=9, read my latest comment in the question – Martini002 – 2017-04-11T00:12:20.883

I will try it again in my MySQL server, just to confirm a misstype from my part, but the first attempt did not work for me, give me a moment please – Martini002 – 2017-04-11T00:28:10.303

I know why it was not working, Select * FROM t1; it is present in your 3th line hahaha, works as expected, many thanks to you – Martini002 – 2017-04-11T00:31:32.560

But, if the RowID is not secuential? If I delete ID 5 it can not show the RowID 6 – Martini002 – 2017-04-11T00:52:11.827

0

A better version of Moderator Impersonator answer would be:

SELECT * FROM numbers WHERE id IN (SELECT ID+1 FROM numbers WHERE N1 = 9)

Martini002

Posted 2017-04-10T22:01:51.997

Reputation: 43

I also updated my answer with this detail from this answer for you. – Pimp Juice IT – 2017-04-11T01:05:32.387

I posted the new question Here

– Martini002 – 2017-04-11T01:10:01.760