参考 https://stackoverflow.com/questions/866465/order-by-the-in-value-list
将结果按ids的顺序排序cn字段举例:
ruby实现
ids = [635, 511, 580]
order_ids = []
ids.each_with_index{|id,index| order_ids << "(#{id}, #{index + 1})"}
# order_ids => "(635, 1),(511, 2),(580, 3)"
City.connection.execute(
"select cities.id,cities.cn
from cities join (values #{order_ids}) as x (id,ordering) on cities.id = x.id
where cities.id IN (#{ids.join(',')})
order by x.ordering"
).to_a
结果:
[ {
"id" => 635,
"cn" => "北京"
},
{
"id" => 511,
"cn" => "成都"
},
{
"id" => 580,
"cn" => "西安"
}
]
网友评论