LoginSignup
3
4

More than 5 years have passed since last update.

【Mysql】相関クエリでつまづいた。検索

Last updated at Posted at 2018-02-01

開発でだいぶ詰まったので、メモ

やりたかったこと

fuelPHPにおいて、サブクエリを用いて親クエリでfromしているtableと同じ場所から情報を抜き出す。
要は以下の感じをfuelPHPのQueryBuilderで行いたかった。

社員の住所がpostで送られてきたワードで検索して情報を返すクエリ
//リクエストで送信された住所検索ワード

$address = $post['address'];

//Mysqlで実行したい生クエリ
select * from staffs 
         where exists(select * from staffs as st
                       where st.address like '%'.$address.'%'
                       and st.id = staffs.id);

ポイントは、サブクエリ内のstaffs as st と 親クエリのstaffsをくっつけてあげること。
これをfuelPHPでやろうとしたら、以下が正解。
今回のケースは、$query(select * from staffs)という親クエリを引数でもらった上でサブクエリを実行する。

結論

staffs.php

public static function get_address(&$query)
{
   $address = Input::post['address'];
   $sub_query = DB::select()->from(array('staffs', 'st'))
                    ->where('st.address', 'like', '%'.$address.'%')
                    ->where(DB::expr('staff.id'), 'st.id');
   $query->where_open();
   $query->where(DB::expr(''), DB::expr('EXISTS'), $sub_query);
   $query->where_close();

   $query->execute();
}

これで解決。
親クエリのfromしているtableをDB::expr()の中に書かないと、ただの文字列として認識されてしまうため、相関クエリとして実行されないという現象でした。

exprメソッドは、生クエリで使用するcountメソッドや、concatメソッドをfuelPHP側で使用する時に使用します。
参考URL:http://fuelphp.jp/docs/1.6/classes/database/db.html

※実際はもっと多くのtableをサブクエリ内で結合してますが、今回の記事の趣旨には関係ない部分で大量の記述が課されることになるので省きました。サブクエリいらなくね?みたいな感じですが、すいません...

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