Tin*_*n81 2 ruby ruby-on-rails ruby-on-rails-3
Ruby中从列中找到最长字符串的最有效方法是什么X?
更新:
这也是有效的:
def self.length_of_longest_number
Invoice.order("LENGTH(number) DESC").first.number.length
end
Run Code Online (Sandbox Code Playgroud)
只是想知道是否有效.如果它适用于MySQL 和 Postgres ......
这也是有效的:
def self.length_of_longest_number
Invoice.order("LENGTH(number) DESC").first.number.length
end
Run Code Online (Sandbox Code Playgroud)
只是想知道是否有效.如果它适用于MySQL 和 Postgres ......
# Change your model name and field to your needs
Participant.order("MAX(CHAR_LENGTH(first_name)) desc").limit(1)
# works too:
Participant.order("MAX(CHAR_LENGTH(first_name)) desc").first
# and this is the most efficient to get the field directly:
Participant.limit(1).order("MAX(CHAR_LENGTH(first_name)) desc").pluck(:first_name)
Run Code Online (Sandbox Code Playgroud)