最近做項目,在做搜索模塊的時候,模糊查詢肯定少不了。
今天就詳細的看一下模糊查詢:
$where['title'] = array('like','%'.$words.'%'); $where['title'] = array('like',array('%'.$words.'%','%'.$wordss.'%')); $where['title'] = array(array('like','%'.$words.'%'),array('like','%'.$wordss.'%'));
一、當個字段做模糊查詢。
$words = "吃"; $where['title'] = array('like','%'.$words.'%'); $list = $TagDB->where($where)->select();
這樣執行的Sql是:
SELECT * FROM `tp_keywords_sanqi` WHERE `title` LIKE '%吃%'
這個可以查詢多個字段:
$where['title'] = array('like','%'.$words.'%'); $where['description'] = array('like','%'.$words.'%'); $list = $TagDB->where($where)->select();
上面的壞處:很多時候,我們做的是標題 title的查詢,而且查詢的時候,要求包含 title 包含兩個或者以上的詞:
例如:
要求一:查詢標題包含 “作用” 或 “怎樣” ;
$words = "怎樣"; $wordss = "作用"; $where['title'] = array('like',array('%'.$words.'%','%'.$wordss.'%')); $list = $TagDB->where($where)->select();
執行的Sql是這樣的:
SELECT * FROM `tp_keywords_sanqi` WHERE (`title` LIKE '%怎樣%' OR `title` LIKE '%作用%')
要求二:查詢標題中同時包含 “作用” 和 ”怎樣“ ;
$words = "怎樣"; $wordss = "作用"; $where['title'] = array(array('like','%'.$words.'%'),array('like','%'.$wordss.'%')); $list = $TagDB->where($where)->select();
執行的sql是這樣的:
SELECT * FROM `tp_keywords_sanqi` WHERE ( `title` LIKE '%怎樣%' AND `title` LIKE '%作用%' )
當然啦!還可以自己寫Sql來執行:
$sql = "SELECT * FROM `tp_keywords_sanqi` WHERE `title` LIKE '%什么%';"; $sql = "SELECT * FROM `tp_keywords_sanqi` WHERE (`title` LIKE '%什么%') OR (`title` LIKE '%吃%');"; $sql = "SELECT * FROM `tp_keywords_sanqi` WHERE (`title` LIKE '%什么%' AND `title` LIKE '%作用%')"; $list = M()->query($sql);
具體示例:
$words = "作用 功效"; $where = array(); $wordsArr = explode(' ',$words); $whereArr = array(); foreach($wordsArr as $k=>$v){ $arr = array(); if(!$v)unset($wordsArr[$k]); array_push($arr,'like'); array_push($arr,'%'.$v.'%'); array_push($whereArr,$arr); } $where['title'] = $whereArr; $list = $TagDB->where($where)->select(); echo $TagDB->getLastSql();
執行的Sql:
SELECT * FROM `tp_keywords_sanqi` WHERE ( `title` LIKE '%作用%' AND `title` LIKE '%功效%' )
目的達到!