适用于需要条件连接并选择:
使用 mysql 的原生条件可能是一个好方法。您可能会遇到这样的情况,如果 PHP 中的特定条件是真实的,那么您需要加入该表,否则不要加入。
例如:
如果 $loggedInUser 是管理员,那么您希望获得学生出勤率,否则只显示分数。
你可以拥有(以下PS为伪代码,仅供参考):
<?php
// Having the column selection only when a particular condition is true
// Else have its value as NULL(You can have NA also)
if($loggedInUser->role == 'admin'){
$attendanceColumnSelect = DB::raw('attendance.total as total_attendance');
}
else{
$attendanceColumnSelect = DB::raw('NULL as total_attendance');
}
// Students query with joins which must be there always
$studentsQuery= Students::select('name', 'class', 'age', $attendanceColumnSelect)
->join('someothertable', 'someothertable.student_id', '=', 'student.id');
// Adding join of attendance only when required for admin role
if($loggedInUser->role == 'admin'){
$studentsQuery->join('attendance', 'attendance.student_id', '=', 'student.id');
}
// Getting final data
$finalResult = $studentsQuery->get();
?>
如果你尝试这样做:
<?php
$finalResult = DB::select("
SELECT students.name,
students.class,
students.age,
IF('$loggedInUser->role' = 'admin', attendance.total, NULL) as total_attendance
FROM students
INNER JOIN someothertable on someothertable.student_id = student.id
INNER JOIN attendance on attendance.student_id = student.id
");
?>
那么即使你知道条件为假,你也必须让出勤加入,否则它会出现“未知列出勤.total”错误。
从我的角度来看,如果我们知道我们不需要特定列,我就不会加入该表。如果你对上面的原始查询做一个 EXPLAIN,你会发现即使 select 中的 If 条件为 false,MySQL 也需要出勤表。
如果您发现此错误或任何更好的建议,请随时发表评论。