如何以相反的顺序从mysql数据库中每次选择2个数据。例如,在此表中
|---------------------|------------------|
| id | category |
|---------------------|------------------|
| 1 | 1 |
|---------------------|------------------|
| 2 | 3 |
|---------------------|------------------|
| 3 | 1 |
|---------------------|------------------|
| 4 | 2 |
|---------------------|------------------|
| 5 | 1 |
|---------------------|------------------|
| 6 | 3 |
|---------------------|------------------|
| 7 | 1 |
|---------------------|------------------|
我想在每次类别为1的情况下以相反的顺序选择2个数据。 对于第一次运行查询,我将获得id = 7和id = 5的数据。对于第二次运行查询,我将获得id = 3和id = 1的数据。如何形成该查询?
答案 0 :(得分:1)
您可以使用不同的(限制)查询:
select id from [your-table-name-here] where category=1 order by id desc limit 0, 2 --to get first two
select id from [your-table-name-here] where category=1 order by id desc limit 2, 2 --to get next two
...
select id from [your-table-name-here] where category=1 order by id desc limit x, x+2 --etc
答案 1 :(得分:0)
除了SQL之外,您还希望使用其他语言来执行此操作。以下是使用PHP的示例:
$query_string = "SELECT `id` FROM `<TABLE NAME>` WHERE `category` = 1 ORDER BY `id` DESC";
$result = mysqli_query($link, $query_string); //where $link stores the connection to your MySQL database
if ($result != null) {
$highest_id = mysqli_fetch_row($result)[0];
$second_row = mysqli_fetch_row($result);
if ($second_row != null) $second_highest_id = $second_row[0];
}
//etc