whereExists分析

whereExists

基础概念

子查询的一种,查询出前面的结果(外部查询)之后,然后将前面的结果查出来的集和后者(内部查询)进行再次查询比较,如果后者中存在那么就可存在

经典格式

    select * from table1 where exists(select * from where table1.id=table2.table_id)
    ---------外部查询-----------------  ---------------内部查询-----------------------

代码分析

使用场景

使用查询出来所有含有学生的班级,没有学生的班级不进行查询

数据表

班级表(student_class)

  • id
  • name

学生表(student)

  • id
  • name
  • age
  • student_id

代码实例

        // 写法一
        $result = DB::table('student_class')
            ->select('id','name')
            ->whereExists(function ($query) {
                return $query
                    ->selectRaw(1)
                    ->from('student')
                    ->whereColumn('student_class.id','student.class_id');
            })
        ->get();

        // 写法二 
        $result = DB::table('student_class')
            ->select('id','name')
            ->whereExists(function ($query) {
                return $query
                    ->selectRaw(1)
                    ->from('student'    )
                    ->whereRaw('student_class.id=student.class_id');
            })
        ->get();

执行的sql分析

select `id`, `name` from `student_class` where exists ( select 1 from `student` where `student_class`.`id` = `student`.`class_id` )

后话

  • whereExist使用时候,传入的参数为闭包函数中,闭包函数中使用DB::table(table)这种方式无效,只可以使用$query->from(table)这种方式。
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容