thinkphp---模糊查詢詳解
阿新 • • 發佈:2018-05-27
包含 RR word words desc key 怎樣 這樣的 -h
最近做項目,在做搜索模塊的時候,模糊查詢肯定少不了。
今天就詳細的看一下模糊查詢:
$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);
thinkphp---模糊查詢詳解