ThinkPHP多表查詢處理
成都創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司一直秉承“誠(chéng)信做人,踏實(shí)做事”的原則,不欺瞞客戶,是我們最起碼的底線! 以服務(wù)為基礎(chǔ),以質(zhì)量求生存,以技術(shù)求發(fā)展,成交一個(gè)客戶多一個(gè)朋友!專注中小微企業(yè)官網(wǎng)定制,網(wǎng)站設(shè)計(jì)制作、成都做網(wǎng)站,塑造企業(yè)網(wǎng)絡(luò)形象打造互聯(lián)網(wǎng)企業(yè)效應(yīng)。
ThinkPHP多表連接查詢處理
ThinkPHP關(guān)聯(lián)查詢(多表查詢)
網(wǎng)上找到三種方法:table()、join()、原生SQL語(yǔ)句查詢。(以下三種方法輸出結(jié)果一致,并且很好的保留了ThinkPHP自己的分頁(yè)功能)
第一種:table()方法
實(shí)例:需要連接查詢兩張表(表agent和表transinfo)
$Model=new Model(); $sqlcount="select count(*) as mycount from agent a ,transinfo t where t.clientId=a.id and t.transType like '%agent%' and a.id in (".$agent_str.")"; $listCount = $Model ->query($sqlcount); $Page = new Page ( $listCount[0][mycount], 2 ); $show = $Page->show (); $list = $Model->table('agent a, transinfo t')->where("t.clientId=a.id and t.transType like '%agent%' and a.id in (".$agent_str.")")->limit ( $Page->firstRow . ',' . $Page->listRows )->select(); //echo $Model->getLastSql(); $this->assign('list',$list);// 賦值數(shù)據(jù)集 $this->assign('page',$show);// 賦值分頁(yè)輸出
第二種:join()方法
實(shí)例:需要連接查詢兩張表(表agent和表transinfo)
$Model=new Model(); $agentModel = $Model->Table("agent"); $listCount = $agentModel->join(" AS a RIGHT JOIN transinfo t ON t.clientId=a.id and t.transType like '%agent%' and a.id in (".$agent_str.")") ->field("count(*) as mycount") ->select(); $Page = new Page ( $listCount[0][mycount], 2 ); $show = $Page->show (); $Model=new Model(); $agentModel = $Model->Table("agent"); $list = $agentModel->join(" AS a RIGHT JOIN transinfo t ON t.clientId=a.id and t.transType like '%agent%' and a.id in (".$agent_str.") order by t.id DESC limit ".$Page->firstRow.",".$Page->listRows) ->field("a.*,t.*") ->select(); //echo $agentModel->getLastSql(); $this->assign('list',$list);// 賦值數(shù)據(jù)集 $this->assign('page',$show);// 賦值分頁(yè)輸出
提示:你也可以這樣實(shí)例化更簡(jiǎn)潔(官方推薦的):$agentModel = M('Agent'); // 實(shí)例化User對(duì)象
第三種:原生SQL語(yǔ)句查詢法
$Model=new Model(); $sqlcount="select count(*) as mycount from agent a ,transinfo t where t.clientId=a.id ".$where. " and t.transType like '%agent%' and a.id in (".$agent_str.")"; $listCount = $Model ->query($sqlcount); $Page = new Page($listCount[0]['mycount'],2);// 實(shí)例化分頁(yè)類 傳入總記錄數(shù)和每頁(yè)顯示的記錄數(shù) $show = $Page->show(); $sqlList="select t.*,a.* from agent a ,transinfo t where t.clientId=a.id ".$where. " and t.transType like '%agent%' and a.id in (".$agent_str.") limit {$Page->firstRow},{$Page->listRows}"; $list = $Model ->query($sqlList); $this->assign('list',$list);// 賦值數(shù)據(jù)集 $this->assign('page',$show);// 賦值分頁(yè)輸出
參考資料:
http://hi.baidu.com/wjlhh001/item/18d9a91031081b5e2a3e22af
http://www.yunda51.com/304.html
http://www.w3school.com.cn/sql/sql_join_right.asp
END