CodeIgniter 活动记录 SELECT 查询,带有 JOIN 和 WHERE IN 子查询

问题描述 投票:0回答:4

我正在尝试发送此查询:

SELECT * FROM employees
INNER JOIN authorization ON authorization.Employee_ID=employees.Employee_ID
WHERE authorization.role='Team Leader'
AND authorization.Employee_ID NOT IN(SELECT Employee_ID FROM team_leaders)

此查询用于选择具有团队领导职位(角色)但未分配到团队的员工。

我在 CodeIgniter 的活动记录中执行此查询时遇到问题

我的错误型号代码:

function teamleaders()
{
    $this->db->select('Employee_ID');
    $this->db->from('team_leaders');
    $query=$this->db->get();
    $teamleaderid=$query->result_array();
        //get teamleaders id who are assigned in a team
    
    $this->db->select('employees.Employee_ID,employees.First_Name,employees.Last_Name');
    $this->db->from('employees');
    $this->db->join('authorization','authorization.Employee_ID=employees.Employee_ID');
    $this->db->where('authorization.role','Team Leader');
    $this->db->where_not_in('authorization.Employee_ID',$teamleadersid);
    $query=$this->db->get();

    return $query->result_array();
}
php codeigniter join subquery query-builder
4个回答
1
投票

是的,你可以尝试一下,

   $this->db->select('employees.*');
   $this->db->from('employees');
   $this->db->join('authorization','authorization.Employee_ID=employees.Employee_ID');
   $this->db->where('authorization.role','Team Leader');
   $this->db->where('authorization.Employee_ID NOT IN (SELECT Employee_ID FROM team_leaders)');
   $query=$this->db->get();

0
投票

这个怎么样:

$sql="SELECT * FROM employees
INNER JOIN authorization ON authorization.Employee_ID=employees.Employee_ID
WHERE authorization.role='Team Leader'
AND authorization.Employee_ID NOT IN(SELECT Employee_ID FROM team_leaders)";

return $this->db->query($sql)->result_array();

0
投票

您的

$teamleaderid
数组的格式与您认为的格式不同。它是数组的数组,而不是 ID 的数组。

试试这个:

$teamleaderid = array_map(function($a){
    return $a['Employee_ID'];
}, $teamleaderid);

0
投票

可以通过利用 LEFT JOIN 并检查 team_leaders 表中的 NULL 行来避免子查询。

明智的做法是避免将数组传递给

where_in()
where_not_in()
;当数组为空时,CodeIgniter 将创建无效/空
IN()
条件。

以下内容应成功返回

role
Team Leader
但在
team_leaders
表中未找到的员工。

public function teamleaders(): array
{
    return $this->db
        ->select('e.*')
        ->join('authorization a', 'e.Employee_ID = a.Employee_ID')
        ->join('team_leaders tl', 'e.Employee_ID = tl.Employee_ID', 'LEFT')
        ->where('a.role', 'Team Leader')
        ->where('tl.Employee_ID IS NULL')
        ->get('employees e')
        ->result_array();
}
© www.soinside.com 2019 - 2024. All rights reserved.