MySQL多表联查之ThinkPHP中的实现

创建两个表如图:

sp_user表:

sp_dept表:

目的:通过sp_user的dept_id查询所属部门即sp_dept中的name。

原生sq方法一:select t1.*,t2.name as deptname from sp_user as t1,sp_dept as t2 where t1.dept_id = t2.id;

原生sq方法二:select t1.*,t2.name as deptname from sp_user as t1 left join sp_dept as t2 on t1.dept_id = t2.id;

结果相同:

对应ThinkPHP中,则也有两种方法table和join如下:

 1 //多表联查(table)
 2     public function test18() {
 3         //实例化模型
 4         $model = M();
 5         //查询
 6         $result = $model->field('t1.*, t2.name as deptname')->table('sp_user as t1, sp_dept as t2')
             ->where('t1.dept_id = t2.id')->select(); 7 dump($result); 8 } 9 //多表联查(join) 10 public function test19() { 11 //实例化模型 12 $model = M('User'); 13 //查询 14 $result = $model->field('t1.*, t2.name as deptname')->alias('t1')
             ->join('left join sp_dept as t2 on t1.dept_id = t2.id')->select(); 15 dump($result); 16 }

测试结果相同:

 

综上:ThinkPHP进行多表联查可通过table方法和join方法分别实现,测试环境ThinkPHP3.2.3,表前缀sp_

posted @ 2018-09-10 15:58  昊晗远昂  阅读(563)  评论(0编辑  收藏  举报