美文网首页
sql ORDER BY the IN value list (

sql ORDER BY the IN value list (

作者: ifree321 | 来源:发表于2020-06-16 18:35 被阅读0次

参考 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" => "西安"
    }
]

相关文章

网友评论

      本文标题:sql ORDER BY the IN value list (

      本文链接:https://www.haomeiwen.com/subject/pijnzhtx.html