我有以下SQL表(在MySQL中):
students +-----+------------+ | id | first_name | +-----+------------+ | 01 | John | +-----+------------+ | 02 | Jane | +-----+------------+ | 03 | Peter | +-----+------------+ academics +-----+-----------+----------+------+ | id | year_start| year_end |status| +-----+-----------+----------+------+ | 10 | 2016 | 2017 |1 | +-----+-----------+----------+------+ | 20 | 2017 | 2018 |0 | +-----+-----------+----------+------+ enrollments +----+------------+-------------+ | id | student_id | academic_id | +----+------------+-------------+ | 1 | 01 | 10 | +----+------------+-------------+ | 2 | 02 | 20 | +----+------------+-------------+ | 3 | 01 | 20 | +----+------------+-------------+
如何获得来自学生students table和enrollments table谁没有报名参加本学年或谁没有记录在存在的enrollments table当前学年。
students table
enrollments table
现在,我可以使用以下查询获取学生表单,该表单students table中没有注册详细信息enrollments table:
$students = \DB::table('students') ->select( 'students.id', 'first_name' ) ->leftJoin('enrollments','enrollments.student_id','=','students.id') ->whereNull('enrollments.student_id') ->get();
根据上表中的数据,此查询将返回student Peter - 03。
Peter - 03
但是如何获得当前学年没有入学详细信息的学生?
这是我确定本学年的方式:
$current_academic = Academic::where('status', 1)->first();
使用现有查询,我如何加入,academics table以便可以查询出当前学年没有入学记录的学生。将不胜感激您的认真回答和建议。
academics table
$current_academic = Academic::where('status', 1)->first(); $students = \DB::table('students') ->select( 'students.id', 'first_name' ) ->whereNotExists( function ($query) use ($current_academic) { $query->select(DB::raw(1)) ->from('enrollments') ->whereRaw('students.id = enrollments.student_id') ->where('enrollments.academic_id', '=', $current_academic->id); }) ->get();
让我们给出一些细节:
1-whereNotExists子句将仅返回子查询中没有任何行的学生。
whereNotExists
2-子查询选择注册表中存在的学生,并且他们的Academics_id为10
希望这可以帮助