如何从MySQL表的有序id列表中获取有序行列表?

时间:2022-09-25 15:39:01

I'm working in PHP, and I have a list of ids, which are ranked, with the first being the most important. I'm retrieving the rows using something like this (simplified for clarity):

我在PHP中工作,我有一个id列表,它是排序的,第一个是最重要的。我用这样的东西来检索行(为了清晰起见,简化):

$id_as_sql_list = implode("','", $id_list);

$sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list')";

This basically works out as:

这基本上是这样的:

WHERE id in ('456', '123', '789')

The problem is, the result from the database isn't coming back in the order of the list. What's the best way to get them back in this order?

问题是,来自数据库的结果不会按照列表的顺序返回。什么是最好的方式让他们回到这个顺序?

3 个解决方案

#1


4  

Take a look at order by field syntax.

根据字段语法查看顺序。

This is an example

这是一个例子

select * from table
where id in (x,y,z)
order by field(id,x,y,z)

#2


0  

$sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list')
ORDER BY YourRankingField ";

#3


0  

use ORDER BY

使用命令

$sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list') ORDER BY whatever";

where whatever is the field you wish to order by.

你要订购的场地在哪里?

#1


4  

Take a look at order by field syntax.

根据字段语法查看顺序。

This is an example

这是一个例子

select * from table
where id in (x,y,z)
order by field(id,x,y,z)

#2


0  

$sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list')
ORDER BY YourRankingField ";

#3


0  

use ORDER BY

使用命令

$sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list') ORDER BY whatever";

where whatever is the field you wish to order by.

你要订购的场地在哪里?