Milk+ea

Weblog Is My Hobby.

Sequelのデータセットで使うSQLメソッド

Sequelでデータベースにアクセスするためにデータセットというモノを使います。

データセットの基本形

こんなの。

# sqliteデータベースにアクセス。(test.dbファイル)
# DB = Sequel.connect('sqlite://test.db')
DB[:テーブルの名前]

この形はSQLselect * from テーブルの名前と同じ意味になります。
データセットはこの後ろにSQLメソッドを繋げてより詳しいSQLにします。

いろんな条件をつける

データセットは変数に入れれます。
とりあえず、何度もDB[:***]とするのはめんどくさいので変数に入れます。

dataset = DB[:テーブルの名前]

dataset.SQLメソッド()な形で使っていきます。
以降テーブルの名前をtablesに。


取ってくる列の指定 .select

dataset.select(:col1, :col2)
# => select 'col1', 'col2' from tables

取ってくるデータの条件 : .where .grep .exclude .invert

dataset.where(col: 'val')
# => select * from tables where ('col' = 'val')
dataset.where('col > ?', 1)
# => select * from tables where (col > 1)
dataset.where(:col)
# => select * from tables where 'col'
dataset.grep(:col, '%val%')
# => select * from tables where ((`col` LIKE '%val%' ESCAPE '\\'))

# 復数のwhereを使う
# AND
dataset.where().where()…
# OR
dataset.where().or()

.filterでも同じ

whereの逆にexcludeやinvertがあります。

dataset.exclude(col: 'val')
dataset.where(col: 'val').invert
# => select * from tables where ('col' != 'val)

取ってくる行数の指定 .limit .offset

dataset.limit(10)
# => select * from tables limit 10
dataset.limit(10).offset(5)
dataset.offset(5).limit(10)
dataset.limit(10, 5)
# => select * from tables limit 10 offset 5

取ってくる行の順番 .order

dataset.order(:col)
# => select * from tables order by 'col'
dataset.order(Sequel.asc(:attr))
# => select * from tables order by 'col' asc

取ってきたデータをグループ化 .group

dataset.group(:col)
# => select * from tables group by 'col'

そのグループ化する条件 .having

dataset.group(:col).having(col: 10)
# => select * from tables group by 'col' having 'col' = 10

ただこれらはデータセットを返すだけなので実際にデータを取得するにはアクションメソッドと呼ばれる.allなどを後ろに付ける必要があるよう。

続く(→アクションメソッド