Ruby从列X
中找到最长字符串的最有效方法是什么?
更新:
这也很有效:
def self.length_of_longest_number
Invoice.order("LENGTH(number) DESC").first.number.length
end
只是想知道是否有效。如果它适用于MySQL 和 Postgres ......
答案 0 :(得分:7)
这也很有效:
def self.length_of_longest_number
Invoice.order("LENGTH(number) DESC").first.number.length
end
只是想知道是否有效。如果它适用于MySQL 和 Postgres ......
答案 1 :(得分:6)
# 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)