LEFT JOIN与表一起两次以获得单独的记录

时间:2016-10-16 10:15:07

标签: mysql join group-by left-join aggregate-functions

我试图通过employees表加入attendance_chart表来获取所有员工缺席和现在的总数,其中attendance_status表包含SELECT e.id AS employee_id, COUNT(present_days_chart.id) as present_days_count, COUNT(absent_days_chart.id) as absent_days_count FROM employees e LEFT JOIN attendance_chart present_days_chart ON e.id = present_days_chart.attendance_for_employee_id AND present_days_chart.attendance_status = 'present' LEFT JOIN attendance_chart absent_days_chart ON e.id = absent_days_chart.attendance_for_employee_id AND absent_days_chart.attendance_status = 'absent' WHERE e.id IN (106,138) GROUP BY e.id 中的状态记录}列

class Admin extends CI_Controller {

  public function __construct()
  {
    parent::__construct();
  }

  public function index()
  {
    $this->load->view('dashboard');
  }

  public function Post()
  {
    $this->load->view('add_post');
  }

}

但是,查询会在每行的present_days_count和absent_days_count列中返回相同数量的记录。

我做错了什么?

2 个答案:

答案 0 :(得分:5)

尝试使用CASE WHENSUM

SELECT e.id,
       SUM(CASE WHEN days_chart.attendance_status = 'present' THEN 1 ELSE 0 END) AS present_days_count , 
       SUM(CASE WHEN days_chart.attendance_status = 'absent' THEN 1 ELSE 0 END) AS absent_days_count

FROM employees e
LEFT JOIN attendance_chart days_chart ON e.id = days_chart.attendance_for_employee_id
WHERE e.id in (106,138)
GROUP BY e.id

使用此SUM + CASE WHEN结构,它应计算具有特定attendance_status的每条记录,并在SUM和{GROUP BY的帮助下总结所有计数{1}}

答案 1 :(得分:0)

您是否尝试过稍微改写它?

    SELECT
    e.id AS employee_id,
    COUNT(present_days_chart.id) as present_days_count,
    COUNT(absent_days_chart.id) as absent_days_count

FROM
    employees e
    LEFT JOIN (SELECT * FROM attendance_chart WHERE attendance_status = 'present') AS present_days_chart ON e.id = present_days_chart.attendance_for_employee_id
    LEFT JOIN (SELECT * FROM attendance_chart WHERE attendance_status = 'absent') AS absent_days_chart ON e.id = absent_days_chart.attendance_for_employee_id

WHERE
    e.id IN (106,138)

GROUP BY
    e.id