Answer the question
In order to leave comments, you need to log in
MySQL - how to make a query to select the two extremes?
In a DB for example 100 articles.
Knowing the ID of one of the articles, you need to get the previous and next ones.
I will give an example: there is an article ID = 47.
As a result of the request, we should get the 46th and 48th records.
There is one exception, if we are on the 100th article, then we need to get the 99th and 1st record, i.e. round.
The same applies to the 1st entry. If article ID = 1, then the result should be: 2nd and 100th records
You can write an example query if you have come across it before, or perhaps you have an idea for solving the problem
Answer the question
In order to leave comments, you need to log in
something like this
$current_id = 47;
$next_article = $mysqli->query("select `id` from `articles` where `id` = (select MIN(`id`) from `articles` where `id` > '$current_id')");
$prev_article = $mysqli->query("select `id` from `articles` where `id` = (select MAX(`id`) from `articles` where `id` < '$current_id')");
Considering that the autoincrement id can be "leaky", you can get the next element like this:
and the previous one like this:
At the same time, given that CURRENT_ID is the ID of the current element, and the sorting is the same in all three queries.
It is possible to combine three queries into one using BETWEEN and LIMIT 3.
But it's hard to make cycling at the level of just the database.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question