简体   繁体   English

在Rails中对字符串字段的一部分进行SQL查询的最简单方法是什么?

[英]What is the simplest way to order results from a SQL query on part of a string field in Rails?

Consider a table with a text field with the following form: 考虑一个带有以下形式的文本字段的表:

"foo,bar"

EDITS: "bar" is the first string after the comma. 编辑:“bar”是逗号后面的第一个字符串。 There is only one comma. 只有一个逗号。

What is the simplest way to order by bar ? 什么是最简单的bar订购方式? It can be in either SQL (PostgreSQL) or Ruby. 它可以是SQL(PostgreSQL)或Ruby。

MyTable.all.sort_by { |r| r.my_text.match(/,(.*)$/)[1] }

You can do it inside the database like this: 您可以在数据库中执行此操作:

M.order("substring(c from ',.*$')")

where M is your model and c is the column in question. 其中M是你的模型, c是有问题的列。 The substring call leaves the comma in the substring but that won't alter the sorting and comparing the commas during sorting will probably be faster than trying to remove them. substring调用在子字符串中保留逗号但不会改变排序,并且在排序期间比较逗号可能比尝试删除它们更快。 Also, that form of PostgreSQL's substring should work in 8.2 so it should work with a Heroku shared database. 此外,PostgreSQL的substring形式应该在8.2中工作,因此它应该与Heroku共享数据库一起使用。

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

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