简体   繁体   English

Mysql Codeigniter Active Record - 如何进行where_in查询并返回正确的结果顺序?

[英]Mysql Codeigniter Active Record - How do I do a where_in query and return the correct order of results?

I have a set of IDs passed in a particular order which needs to be retained. 我有一组以特定顺序传递的ID,需要保留。 I am querying from several left joins the data related to each ID. 我从几个左连接查询与每个ID相关的数据。 The IDs are returned from a search so the order must be kept to make the results valid (otherwise it makes searching rather pointless). 从搜索中返回ID,因此必须保留顺序以使结果有效(否则会使搜索变得毫无意义)。

My code looks something like; 我的代码看起来像;

$this->db->where_in('id', $array_of_ordered_ids);

For example - 例如 -

$this->db->where_in('id', array(4,5,2,6));

Will return the results in order 2,4,5,6. 将按顺序返回结果2,4,5,6。

I'd like for it to retain the order and return the results 4,5,2,6. 我希望它保留订单并返回结果4,5,2,6。

Thank you, 谢谢,

To order the result by the order in your array, you can do the following: 要按数组中的顺序对结果进行排序,可以执行以下操作:

$array_of_ordered_ids = array(4,5,2,6);

As you already know the order of the numbers, you can use the Mysql FIELD() Docs function: 正如您已经知道数字的顺序,您可以使用Mysql FIELD() Docs函数:

ORDER BY FIELD(id, 4, 5, 2, 6);

To create such a string, you can use implode Docs : 要创建这样的字符串,您可以使用implode Docs

$order = sprintf('FIELD(id, %s)', implode(', ', $array_of_ordered_ids));

Give it a try: 试试看:

$array_of_ordered_ids = array(4,5,2,6);
$this->db->where_in('id', $array_of_ordered_ids);
$order = sprintf('FIELD(id, %s)', implode(', ', $array_of_ordered_ids));
$this->db->order_by($order); 

As all answers I found on SO where just semi correct but all gave good hints I implemented successfully the code to retrieve set of rows correct ordered by the order in given array. 正如我在SO上找到的所有答案都只是半正确但所有提供了良好的提示我成功实现了代码以检索由给定数组中的顺序正确排序的行集。

To Produce a sql like this: 要生成这样的sql:

SELECT * FROM (`product`) WHERE `id` IN (2, 34, 234) 
ORDER BY FIELD(`id`, 2, 34, 234)

use this code, while $ids contains the array (2, 34, 234). 使用此代码,而$ ids包含数组(2,34,234)。

// select from ... 
$this->db->where_in('id',$ids);
$this->db->_protect_identifiers = FALSE; // stop CI adding backticks
$order = sprintf('FIELD(id, %s)', implode(', ', $ids));
$this->db->order_by($order);
$this->db->_protect_identifiers = TRUE; // switch on again for security reasons
// get...

see also here: http://ellislab.com/forums/viewthread/137157/#1058666 另见: http//ellislab.com/forums/viewthread/137157/#1058666

Thank for biggest solution. 感谢最大的解决方案。

 $orde_num_string = implode(",",$order_num);
            $this->db->where_in("cir_order.order_num",$order_num);
            $this->db->_protect_identifiers = FALSE;
            $this ->db->order_by("FIELD(cir_order.order_num, $orde_num_string)");
            $this->db->_protect_identifiers = TRUE;

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

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