小编典典

Laravel-从一个表中获取不存在的记录,并附加一个where子句

sql

我有以下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 tableenrollments 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

但是如何获得当前学年没有入学详细信息的学生?

这是我确定本学年的方式:

$current_academic = Academic::where('status', 1)->first();

使用现有查询,我如何加入,academics table以便可以查询出当前学年没有入学记录的学生。将不胜感激您的认真回答和建议。


阅读 290

收藏
2021-04-22

共1个答案

小编典典

$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子句将仅返回子查询中没有任何行的学生。

2-子查询选择注册表中存在的学生,并且他们的Academics_id为10

希望这可以帮助

2021-04-22