LoginSignup
3
3

More than 5 years have passed since last update.

[Rails] 指定したレコードの取得 (条件 A でソートし、かつ条件 B に一致するデータの取り出し)

Posted at

以下のようなレコードを持った Student テーブルがあると仮定

id class score
3 10 2
4 1 4
5 1 5
6 1 4
7 1 4
8 1 3

score でソートし、かつ class が 1 であるもののみを取り出す

Student.order("score").where(class: 1)
  • 結果
id class score
8 1 3
4 1 4
6 1 4
7 1 4
5 1 5

score のソートを降順にする

Student.order("score DESC").where(class: 1)
id class score
5 1 5
7 1 4
6 1 4
4 1 4
8 1 3

score で降順にソートし、1 つめを取り出す

Student.limit(1).order("score DESC").where(class: 1)
id class score
5 1 5
3
3
0

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
3
3