0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Rails][PostgreSQL] A-1, B-2 のように文字列と整数を結合した文字列で ORDER BY したい

Last updated at Posted at 2019-10-17

バージョン情報

$ psql --version                                                                                                                                                                                                                             
psql (PostgreSQL) 11.3

$ bin/rails -v
Rails 6.0.0

やりたいこと

Item.pluck(:code)
# => ["A-1", "B-10", "B-1", "A-10", "A-2", "B-2"]

これを ORDER BY 句を使って

["A-1", "A-2", "A-10", "B-1", "B-2", "B-10"]

の順番に並べたい。

ただ order(:code) を呼ぶだけだと

["A-1", "A-10", "A-2", "B-1", "B-10", "B-2"]

となってしまう :sob:

方法

split_part 関数を使う。

split_part(string text, delimiter text, field int)
string を delimiter で分割し、その結果から (1 から始まるように数える) 指定したフィールドを返します。

また、整数の部分は :: を使って string から integer にキャストする。

Item.order(Arel.sql("split_part(code, '-', 1), split_part(code, '-', 2)::integer")).pluck(:code)
# => ["A-1", "A-2", "A-10", "B-1", "B-2", "B-10"]

もっと効率のよい方法がありそうな予感。他にいい方法があれば教えてください :bow:

参考

0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?