戸田 広
info****@sciss*****
2012年 7月 3日 (火) 21:06:34 JST
こんばんは、戸田です。
On 2012/07/03, at 10:13, 小島健太郎 wrote:
> モデルで下記のSQLを使用していますが
> 最終行のorwhere分を追加すると、返される結果が0件となってしまいます。
>
> function getAll($index_no,$index_no_first,$index,$dept_id){
>
> $this->db->select("*");
> $this->db->from("t_reply");
> $this->db->join("M_dept","T_reply.dept=M_dept.dept_id","left");
> $this->db->like("T_reply.index_no",$index_no,"after");
> $this->db->like("T_reply.index_name",$index);
> $this->db->where("T_reply.dept",$dept_id);
> $this->db->orwhere("T_reply.index_no_first",$index_no_first);//←問題の行
>
> return $this->db->get();
> }
1.7.3 の環境で、全く同じメソッドを持つモデルクラスを作って
試しに CLI で、MySQL データベースドライバーで実行しましたが、
プロファイラーは次のようなSQL文を表示しました(見やすいよう整形しています)。
========================================
SELECT
*
FROM
(`t_reply`)
LEFT JOIN
`M_dept`
ON
`T_reply`.`dept`=`M_dept`.`dept_id`
WHERE
`T_reply`.`dept` = 1
OR
`T_reply`.`index_no_first` = '2'
AND
`T_reply`.`index_no` LIKE '2.5%'
AND
`T_reply`.`index_name` LIKE '%1%'
;
========================================
> SELECT *
> FROM (`t_reply`)
> LEFT JOIN `M_dept` ON `T_reply`.`dept`=`M_dept`.`dept_id`
> WHERE `T_reply`.`index_no_first` = '2'
> AND `T_reply`.`index_no` LIKE '2.5%'
この結果では、次の2つの文が実行されていないように見えます。
これはなぜなのでしょうか? お心当たりありますか?
> $this->db->like("T_reply.index_name",$index);
> $this->db->where("T_reply.dept",$dept_id);
また、使用したデータベースドライバーは何でしょうか?
なお、orwhere() は or_where() に引数を渡すだけのエイリアスですので
or_where() と同じ結果になります。
> また、SQL文で微妙に括弧()を操作したいとき
> 何か記述方法はあるのでしょうか?
Active Record を使わないのでよろしければ、
query() を使った方が手っ取り早いと思います。
以上です。
> そこでコントローラに
> $this->output->enable_profiler(true);
> と記述して、生成されたSQL文を確認したところ
> 下記のように、AND条件の一部に組み込まれていました。
>
> SELECT *
> FROM (`t_reply`)
> LEFT JOIN `M_dept` ON `T_reply`.`dept`=`M_dept`.`dept_id`
> WHERE `T_reply`.`index_no_first` = '2'
> AND `T_reply`.`index_no` LIKE '2.5%'
>
> 使用しているバージョンが1.7系のため、
> 「or_where」ではなく「orwhere」と書いています。
> (ちなみにor_whereと書いても結果は同じでした。)
>
> OR文を何とかして書きたいのですが
> 上記に使い方の間違いなどありますでしょうか?
>
> また、SQL文で微妙に括弧()を操作したいとき
> 何か記述方法はあるのでしょうか?
> 宜しくお願いいたします。
>
> _______________________________________________
> Codeigniter-users mailing list
> Codei****@lists*****
> http://lists.sourceforge.jp/mailman/listinfo/codeigniter-users