This might be a duplicated question of mysql union vs multiple queries except the question is too general, and this question for specified case.
First of all, there are two options that I am thinking which one is better in term of performance wise. First one is getting previous and next row with separated query. The following is a pseudo code:
sql->query("SELECT * FROM tbldata WHERE id < 3 ORDER BY id DESC LIMIT 1");
$prev = sql->getRecord();
sql->query("SELECT * FROM tbldata WHERE id > 3 ORDER BY id LIMIT 1");
$next = sql->getRecord();
Another solution is to use only one query with UNION.
sql->query("(SELECT * FROM tbldata WHERE id > 3 ORDER BY id DESC LIMIT 1) UNION
(SELECT * FROM tbldata WHERE id < 3 ORDER BY id LIMIT 1)");
$row = sql->getRecords();
if (count($row) > 1) {
$prev = $row[0];
$next = $row[1];
} elseif (count($row) == 0) {
} elseif ($row[0]->id > 3) {
$next = $row[0];
} else {
$prev = $row[0];
}
Which one is a best practice for this type of problem?