Verification: a143cc29221c9be0

Order by desc sql php

Таблица с данными

+----+------------+-------------+---------------------+
| id | name       | category_id | created_at          |
+----+------------+-------------+---------------------+
|  1 | Article 1  |           1 | 2021-01-01 17:05:35 |
|  2 | Article 2  |           1 | 2021-01-02 17:05:35 |
|  3 | Article 3  |           4 | 2021-01-03 17:05:35 |
|  4 | Article 4  |           2 | 2021-01-04 17:05:35 |
|  5 | Article 5  |           3 | 2021-01-04 17:10:35 |
|  6 | Article 6  |           2 | 2021-01-04 17:15:35 |
|  7 | Article 7  |           4 | 2021-01-07 17:05:35 |
|  8 | Article 8  |           3 | 2021-01-08 17:05:35 |
|  9 | Article 9  |           3 | 2021-01-09 17:05:35 |
| 10 | Article 10 |           2 | 2021-01-10 17:05:35 |
+----+------------+-------------+---------------------+

Получить следующую запись

Входящие данные:

$id = 4;
$category_id = 2;
$created_at = '2021-01-04 17:05:35';

SQL запрос:

SELECT *
FROM `article`
WHERE (`id` > $id 
	AND `category_id` = $category_id
	AND `created_at` > $created_at)
ORDER BY `created_at` ASC, `id` ASC
LIMIT 1

Результат:

+----+-----------+-------------+---------------------+
| id | name      | category_id | created_at          |
+----+-----------+-------------+---------------------+
|  6 | Article 6 |           2 | 2021-01-04 17:15:35 |
+----+-----------+-------------+---------------------+

Получить предыдущую запись

Входящие данные:

$id = 6;
$category_id = 2;
$created_at = '2021-01-04 17:15:35';

SQL запрос:

SELECT *
FROM `article`
WHERE (`id` 

Результат:

+----+-----------+-------------+---------------------+
| id | name      | category_id | created_at          |
+----+-----------+-------------+---------------------+
|  4 | Article 4 |           2 | 2021-01-04 17:05:35 |
+----+-----------+-------------+---------------------+