SELECT

where句を設定する

 $rs->search({ age => 20 })                        # WHERE age = 20                   =
 $rs->search({ age => {'>' => 20} })               # WHERE age > 20                   >
 $rs->search({ age => undef })                     # WHERE age is NULL                NULL
 $rs->search([{ age => 20 },{ age => 30 }])        # WHERE age = 20 OR age = 30       OR
 $rs->search({ age => 20, name => 'taro })         # WHERE age = 20 AND name = 'taro' AND
 $rs->search({ 'age' => { '>' => 10, '<' => 20 }}) # WHERE age > 10 AND age < 20      AND  同じカラムを使う場合
 $rs->search_like({ name => '%taro%' })            # WHERE name LIKE '%taro%'         LIKE
 $rs->search({id => {-in => \@ids}})               # WHERE id in (1,2,3..)            IN

http://search.cpan.org/perldoc?DBIx::Class::ResultSet#search

検索を実行する

順次取り出す

 my $rs = $schema->resultset('User')->search({ age => 20});
 while (my $user = $rs->next) { print $user->name; }

1行だけ取り出す

 my $user = $schema->resultset('User')->single({ age => 20});

最初の行を取り出す

 my $user = $schema->resultset('User')->search({ age => 20})->first;

全行取り出す

 my @users = $schema->resultset('User')->search({ age => 20})->all;

プライマリキーで検索する

 my $user = $schema->resultset('User')->find(5);

見つからないときはundefが返ってくる。

ORDER BY

 $rs->search({},{ 
  order_by => [ 'name', { -desc => 'id' } ] # ORDER BY name ASC, id DESC
  });                                       # 'name' は { -asc => 'name' } の省略形                     

http://search.cpan.org/perldoc?SQL::Abstract#ORDER_BY_CLAUSES

NULLを0と見なしてORDER BYする方法

(多分)DBICではCASE式が使えないので、COALESCE関数を使う。例えばpointカラムを降順でソートするには以下のようにする。

 $rs->search(undef, {
  order_by => [ { '-desc' => \'COALESCE(point, 0)' } ],
 });

GROUP BY

 $rs->search({},{
     select   => ['name', {SUM => 'point'}],
     as       => ['name', 'point'],
     group_by => ['name'],
 });
 $point = $rs->next->get_column('point');

COUNT()

 $rs = $rs->search();
 print $rs->count;

↓SELECT COUNT(DISTINCT name) FROM user

 $rs = $rs->seach({},{
   select => [ { count => { distinct => 'name' } } ],
    as    => ['count'],
 });
 print $rs->next->get_column('count');

LIMIT / OFFSET

 $rs->search({},{ order_by => 'id' })->slice(0,20); # slice($offset,$limit)

特定のカラムのみSELECT(AS演算子)

 $rs->search({},{
    select => [ 'name', 'age' ],
    as     => [ 'name', '年齢'],
 });
 print $r->name, $r->get_column('年齢');

ROWオブジェクトからカラム名と値を取得する

 my %user_data = $user->get_columns;

参考

http://search.cpan.org/perldoc?DBIx::Class::Row

DB関数

sum()

 # SELECT sum(point) AS total_point FROM t1;
 $rs = $rs->search(
     {},
     {
         select => [ { sum => 'point' } ],
         as     => ['total_point'],
     }
 );
 my $total_point = $rs->first ? $rs->first->get_column('total_point') : 0;

DBの関数を比較の対象に使う

 $rs->search({"date_part('year', age(now(), birth_date))" => { '<=' => 18 } }); # 年齢が18歳以下
                                                                                # date_part()とage()はPostgreSQLの関数

http://search.cpan.org/perldoc?DBIx::Class::Manual::Cookbook#Using_SQL_functions_on_the_left_hand_side_of_a_comparison

DBの関数を比較の値に使う

不等号「>」も含めて、スカラリファレンスにする。

 $rs->search( { start_day => \' > now()' } );

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS