Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get records before and after given one?

I have the following table structure:

Id, Message
1, John Doe
2, Jane Smith
3, Error
4, Jane Smith

Is there a way to get the error record and the surrounding records? i.e. find all Errors and the record before and after them.

like image 832
Rod Avatar asked Sep 15 '10 13:09

Rod


People also ask

How do I find previous and next records in SQL?

You can use UNION to get the previous and next record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.

What is before and after in SQL?

You can run custom SQL statements on the target database before and after data is processed. Custom SQL statements are run when the job starts and before any data is processed by the stage. Custom SQL statements are run after all the data has been processed by the stage and just before ending the job.

How do I choose my last record?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.


2 Answers

;WITH numberedlogtable AS
(
SELECT Id,Message, 
ROW_NUMBER() OVER (ORDER BY ID) AS RN
 FROM logtable
)

SELECT Id,Message
FROM numberedlogtable
WHERE RN IN (SELECT RN+i
             FROM numberedlogtable
             CROSS JOIN (SELECT -1 AS i UNION ALL SELECT 0 UNION ALL SELECT 1) n
             WHERE Message='Error')
like image 108
Martin Smith Avatar answered Sep 29 '22 13:09

Martin Smith


WITH    err AS 
        (
        SELECT  TOP 1 *
        FROM    log
        WHERE   message = 'Error'
        ORDER BY
                id
        ),
        p AS
        (
        SELECT  TOP 1 l.*
        FROM    log
        WHERE   id <
                (
                SELECT  id
                FROM    err
                )
        ORDER BY
                id DESC
        )
SELECT  TOP 3 *
FROM    log
WHERE   id >
        (
        SELECT  id
        FROM    p
        )
ORDER BY
        id
like image 23
Quassnoi Avatar answered Sep 29 '22 13:09

Quassnoi