LoginSignup
4
1

More than 5 years have passed since last update.

Ebeanでテーブルを結合し、フィールドの値を比較したい

Posted at

eq()はフィールド = 値

EbeanでWhere句を用いて条件を指定する手段の1つにeqメソッドがあり、テーブルの結合にも利用することが可能です。
しかし、フィールド同士の比較でeqメソッドを使用することは不可能です。

例えば、「親テーブルと結合し、親テーブルのフィールドAとBの値が等しい場合、子テーブルのレコードを取得する」SQLを実行したい場合、

ChildrenModel.where().eq("parent.columnA", "parent.ColumnB").findList();

実際に出力されるSQL文
select
    t0.id c0, t0.text c1, t0.create_time c2, t0.update_time c3, t0.parent_id c8, t1.id c9
from
    children t0
left outer join
    parent t1
on
    t1.id = t0.parent_id
where
    (t1.columnA = 'parent.columnB')

なんと左辺のparent.columnAは、結合したテーブルだと認識されt1.columnAとして変換されますが、右辺のparent.ColumnBがそのままの形で値となってしまっています…

そもそもeqメソッドは、eq(フィールド, 値)のように、渡された値を特定のフィールドから検索するような役割になっているため、上記の目的とは若干違っています。

そこで、raw()メソッドを使用することで、この問題が解決できます。

raw()ならフィールド同士の値を比較できる

ChildrenModel.where().raw("parent.columnA = parent.ColumnB").findList();

実際に出力されるSQL文
select
    t0.id c0, t0.text c1, t0.create_time c2, t0.update_time c3, t0.parent_id c8, t1.id c9
from
    children t0
left outer join
    parent t1
on
    t1.id = t0.parent_id
where
    (t1.columnA = t1.columnB)

ちゃんとフィールド同士の値を比較できているのが確認出来ました!

参考URL

Ebeans where columnA equals columnB in same table - stack overflow

4
1
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
4
1