繁体   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?

我有一组以特定顺序传递的ID,需要保留。 我从几个左连接查询与每个ID相关的数据。 从搜索中返回ID,因此必须保留顺序以使结果有效(否则会使搜索变得毫无意义)。

我的代码看起来像;

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

例如 -

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

将按顺序返回结果2,4,5,6。

我希望它保留订单并返回结果4,5,2,6。

谢谢,

要按数组中的顺序对结果进行排序,可以执行以下操作:

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

正如您已经知道数字的顺序,您可以使用Mysql FIELD() Docs函数:

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

要创建这样的字符串,您可以使用implode Docs

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

试试看:

$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); 

正如我在SO上找到的所有答案都只是半正确但所有提供了良好的提示我成功实现了代码以检索由给定数组中的顺序正确排序的行集。

要生成这样的sql:

SELECT * FROM (`product`) WHERE `id` IN (2, 34, 234) 
ORDER BY FIELD(`id`, 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...

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

感谢最大的解决方案。

 $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