參考 https://stackoverflow.com/questions/866465/order-by-the-in-value-list
將結(jié)果按ids的順序排序cn字段舉例:
ruby實(shí)現(xiàn)
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
結(jié)果:
[ {
"id" => 635,
"cn" => "北京"
},
{
"id" => 511,
"cn" => "成都"
},
{
"id" => 580,
"cn" => "西安"
}
]