我想了解为什么我在join子句上使用我需要的约束时能得到预期的结果,但是如果我执行基本的内部联接然后在条件中附加where子句,则失败。
这是返回预期结果的代码:
php
$departmentLeaders = \DB::table('employees AS e')
->join('departments AS d', 'd.leader_id', '=', 'e.id')
->join('business_units AS bu', 'bu.id', '=', 'd.business_unit_id')
->where('bu.id', '=', $buId)
->select('e.id')
->get();
这是什么都不返回的代码:
php
$departmentLeaders = \DB::table('employees AS e')
->join('departments AS d', 'd.id', '=', 'e.department_id')
->join('business_units AS bu', 'bu.id', '=', 'd.business_unit_id')
->where('bu.id', '=', $buId)
->whereRaw('d.leader_id = e.id')
->select('e.id')
->get();
用于查询的RAW SQL返回预期结果:
sql
select * from `employees` as `e` inner join `departments` as `d` on `d`.`leader_id` = `e`.`id` inner join `business_units` as `bu` on `bu`.`id` = `d`.`business_unit_id` where `bu`.`id` = ?
未返回任何行的查询的RAW SQL:
sql
select * from `employees` as `e` inner join `departments` as `d` on `d`.`id` = `e`.`department_id` inner join `business_units` as `bu` on `bu`.`id` = `d`.`business_unit_id` where `bu`.`id` = ? and d.leader_id = e.id
我已经阅读了这篇文章:SQL join: where clause vs. on clause,根据我的理解,两个查询应该返回相同的结果。
答案 0 :(得分:0)
请更新您的查询
$departmentLeaders = \DB::table('employees AS e')
->join('departments AS d', 'd.id', '=', 'e.department_id')
->join('business_units AS bu', 'bu.id', '=', 'd.business_unit_id')
->where('bu.id', '=', $buId)
->whereRaw('d.leader_id = e.id')
->select('e.id')
->get();
使用
$departmentLeaders = \DB::table('employees AS e')
->join('departments AS d', 'd.id', '=', 'e.department_id')
->join('business_units AS bu', 'bu.id', '=', 'd.business_unit_id')
->where('bu.id', $buId)
->where('d.leader_id', '=', 'e.id')
->select('e.id')
->get();