简体   繁体   English

基于字符串“ 1、5、3、7”的sql查询->保持结果顺序

[英]sql query based on string “1,5,3,7” -> keep order in result

i have a simple php string with some id's. 我有一些ID的简单php字符串。

    $string = "10, 5, 10, 3";

i want to fetch based on these ids some sql, without loosing the order of the ids saved in the string. 我想基于这些ID获取一些sql,而不会丢失保存在字符串中的ID的顺序。 i tryed: 我试过了:

    SELECT * FROM media WHERE ID IN ($string);

but the results are now ordered, and double id's are gone 但结果已排序,并且双编号消失了

    output array:  3, 5, 10

how could i use MYSQL to get the rows like this 我如何使用MYSQL获取像这样的行

    row0 : id=>10, 
    row1 : id=>5,
    row2 : id=>10,
    row3 : id=>3

is there a way doing this without running a query for every id ? 有没有一种方法,而不必为每个id运行查询?

for a better understanding - here my table structure for table called media. 为了更好地理解-这里我的表结构称为媒体。 its for saving uploaded images + description + metadata. 它用于保存上传的图片+说明+元数据。

    id, int
    file, varchar
    description_de, varchar
    description_en, varchar
    size, varchar
    width, int
    height, int

and there is a table "projects" where i store just the image id for a project . 并且有一个表“ projects”,其中我仅存储项目的图像ID。 the structure is complex. 结构很复杂。 nobody need to know here. 没有人需要知道这里。 theres a field "media" where i store the media-ids like this : "1,5,33,9,10,1" to store TWO things. 那里有一个“媒体”字段,我在其中存储这样的媒体ID:“ 1,5,33,9,10,1”来存储两个东西。 first the ORDER of images i wana display. 首先我要显示的图像顺序。 SECOND the image id itself . 第二个图像本身。

i need a query to get the images with basicly all fields from media - in the right ORDER . 我需要查询以从媒体获取基本上具有所有字段的图像-在正确的ORDER中。

its better to handle on the php side. 最好在php端进行处理。 Pass the unique ID's to mysql query and shape the data as per your need. 将唯一的ID传递给mysql查询,并根据需要对数据进行整形。

$x = [['id'=>10, 'name'=>'a'], ['id'=>3, 'name'=>'b'], ['id'=>5, 'name'=>'c'] ];
$order = [10,3,5,10,3,5];

$result = [];
foreach($order as $k => $v){
  foreach($x as $x_a){
    if($x_a['id'] == $v){ $result[$k] = $x_a; break; }
  } 
}
print_r($result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM