You can use UNION to get the previous and next record in MySQL.
The syntax is as follows
(select *from yourTableName WHERE yourIdColumnName > yourValue ORDER BY yourIdColumnName ASC LIMIT 1) UNION (select *from yourTableName WHERE yourIdColumnName < yourValue ORDER BY yourIdColumnName DESC LIMIT 1);
To understand the concept, let us create a table. The query to create a table is as follows
mysql> create table previousAndNextRecordDemo - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > Name varchar(30) - > ); Query OK, 0 rows affected (1.04 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into previousAndNextRecordDemo(Name) values('John'); Query OK, 1 row affected (0.17 sec) mysql> insert into previousAndNextRecordDemo(Name) values('Sam'); Query OK, 1 row affected (0.15 sec) mysql> insert into previousAndNextRecordDemo(Name) values('Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into previousAndNextRecordDemo(Name) values('Bob'); Query OK, 1 row affected (0.17 sec) mysql> insert into previousAndNextRecordDemo(Name) values('Larry'); Query OK, 1 row affected (0.20 sec) mysql> insert into previousAndNextRecordDemo(Name) values('David'); Query OK, 1 row affected (0.14 sec) mysql> insert into previousAndNextRecordDemo(Name) values('Ramit'); Query OK, 1 row affected (0.12 sec) mysql> insert into previousAndNextRecordDemo(Name) values('Maxwell'); Query OK, 1 row affected (0.15 sec) mysql> insert into previousAndNextRecordDemo(Name) values('Mike'); Query OK, 1 row affected (0.14 sec) mysql> insert into previousAndNextRecordDemo(Name) values('Robert'); Query OK, 1 row affected (0.19 sec) mysql> insert into previousAndNextRecordDemo(Name) values('Chris'); Query OK, 1 row affected (0.10 sec) mysql> insert into previousAndNextRecordDemo(Name) values('James'); Query OK, 1 row affected (0.16 sec) mysql> insert into previousAndNextRecordDemo(Name) values('Jace'); Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from previousAndNextRecordDemo;
The following is the output
+----+---------+ | Id | Name | +----+---------+ | 1 | John | | 2 | Sam | | 3 | Carol | | 4 | Bob | | 5 | Larry | | 6 | David | | 7 | Ramit | | 8 | Maxwell | | 9 | Mike | | 10 | Robert | | 11 | Chris | | 12 | James | | 13 | Jace | +----+---------+ 13 rows in set (0.00 sec)
Here is the query to get previous and next record using a single query with UNION
mysql> (select *from previousAndNextRecordDemo WHERE Id > 8 ORDER BY Id ASC LIMIT 1) - > UNION - > (select *from previousAndNextRecordDemo WHERE Id < 8 ORDER BY Id DESC LIMIT 1);
The following is the output
+----+-------+ | Id | Name | +----+-------+ | 9 | Mike | | 7 | Ramit | +----+-------+ 2 rows in set (0.03 sec)