thinkphp3.2框架中where條件查詢用法總結

這篇文章主要介紹了thinkphp3.2框架中where條件查詢用法,總結分析了thinkphp3.2中where條件查詢中常用的各種查詢條件、以及各種複合查詢實現方法,需要的朋友可以參考下

本文實例講述了thinkphp3.2框架中where條件查詢用法。分享給大家供大家參考,具體如下:

thinkphp3.2 where 條件查詢

在連貫操作中條件where的操作有時候自己很暈,所以整理下,有助於使用

查詢條件

支持的表達式查詢,tp不區分大小寫

含義 TP運算符 SQL運算符 例子 實際查詢條件
等於 EQ = $where['id'] = array('EQ','1') id = 2
不等於 NEQ != $where['id'] = array('NEQ','1') id!=2
大於 GT > $where['id'] = array('GT','1') id >1
大於等於 EGT EGT $where['id'] = array('EGT','1') id>=1
小於 < < $where['id'] = array('lt',1) id < 1
小於等於 <= <= $where['id'] = array('elt',1) id<=1
匹配 like like where[′id′]=array(′like′,′where[′id′]=array(′like′,′where['id'] = array('like','begin%')
$where['id'] = array('like','%begin%')
where id like '%begin'
where id like 'begin%'
where id like'%begin%
在範圍內包括倆端值 between 0<=id<=10 $where['id'] = array('between',array('0','10')) where id between 0 and 10
不在範圍內 not between 0 >id and 1o < id $where['id'] = array('not between',array('0','10')) where id not between 0 and 10
在枚舉的值中 in in $where['id'] = array('in',array('1','2','5')) where id in ('1','2','3')
不在枚舉值中 not in not in $where['id'] = array('not in',array('1','2',5)) where id not in ('1','2','5')
exp 表達式查詢,支持SQL語法

exp 是表達式的意思,如果你覺得對於一個值限制條件太多的話就可以用這個

$where['id'] = array('exp','in ( select id from id from tableb)');

複查的查詢語句

有的時候,我們希望通過一次的查詢就能解決問題,這個時候查詢條件往往比較複雜,但是卻比多次查詢庫來的高效。

實在是搞不定的話就直接用$where['_string'] = 'xxxx', 這個代表查詢的時候拼接上 xxx 條件,一次性解決問題

$where['_string'] = 'left join A on A.id = b.id where a.id not in (select id from C)';

1. 區間查詢(一個值得多種情況)

默認是 and

$where['id'] =array(array('neq','8'),array('elt','200'),'and'); // 小於等於200 不等於 8
$where['id'] = array(array('neq','8'),'array('neq','10')','or'); // 不等於8或者不等於10

2. 複合查詢

相當於封裝了新的查詢條件在裏面

$where['a'] = 5;
$where['b'] = 6;
$where['_logic'] = 'or';

sql:where a = 5 or b = 6;

$condition['c'] = '3';
$condition['d'] = '4'
$condition['_logic'] = 'or'
$where['a'] = 9;
$where['_complex'] = $condition;

sql: where a=9 and (c = 3 or d = 4)

根據需求,靈活使用(無限套下去)

3. sql 查詢

如果有設置了讀寫分離的話 query 是查詢 execute是更新保存

M()->query('select * from a');
M()->execute('update a set counts = 3 where id = 1103')

4. 獲取要執行的sql 語句

有的時候條件太複雜,比如 id in(xxxxx),這個xxx就是通過一系列操作獲得的結果,嫌麻煩的就直接 都扔進去,寫sql 又長,就直接獲取sql語句扔進去

1.fetchsql
2.buildsql
3.select(false)

M('user')->fetchsql(true)->select();
M('user')->buildsql();
M('user')->select(false);

更多關於thinkPHP相關內容感興趣的讀者可查看本站專題:《ThinkPHP入門教程》、《thinkPHP模板操作技巧總結》、《ThinkPHP常用方法總結》、《codeigniter入門教程》、《CI(CodeIgniter)框架進階教程》、《Zend FrameWork框架入門教程》及《PHP模板技術總結》。

希望本文所述對大家基於ThinkPHP框架的PHP程序設計有所幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章