为什么我的SQL查询获取的行多于表中的行?

时间:2015-11-29 08:54:45

标签: mysql select

salary_sheet表中有35行,但此查询获取30660行,不知道为什么?

 function queryCheck() {
  $sql = "select  salary_sheet.payment_period_id,salary_sheet.employee_id,salary_sheet.supervisorwise_serial,"
."salary_sheet.employee_type_id,salary_sheet.sl,salary_sheet.cl,salary_sheet.el,salary_sheet.basic,salary_sheet.hr,"
."salary_sheet.medical,salary_sheet.other,salary_sheet.total,salary_sheet.min_wages,"
."salary_sheet.prod_wages,salary_sheet.attn_bonus,salary_sheet.prod_bonus,"
."salary_sheet.ot_hours,salary_sheet.ot_rate,salary_sheet.ot_amount,salary_sheet.stamp_deduct,"
."salary_sheet.absent_deduction,salary_sheet.net_payable,"

."employee.employee_code,employee.employee_name,employee.designation_id,employee.employee_grade,"

."attendance_summery.working_days "
."from salary_sheet "
."left join employee on salary_sheet.employee_id = employee.employee_id  "
."left join attendance_summery on salary_sheet.payment_period_id = attendance_summery.payment_period_id    "
."where salary_sheet.employee_type_id = 9 and salary_sheet.payment_period_id = 41  "             
."order by salary_sheet.supervisorwise_serial desc";
$query = $this->db->query($sql);
$rows = $query->num_rows();
return $rows;

 }

有人的帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

这是您的查询。

select  salary_sheet.payment_period_id,
salary_sheet.employee_id,
salary_sheet.supervisorwise_serial,
salary_sheet.employee_type_id,salary_sheet.sl,salary_sheet.cl,salary_sheet.el,salary_sheet.basic,salary_sheet.hr,
salary_sheet.medical,salary_sheet.other,salary_sheet.total,salary_sheet.min_wages,
salary_sheet.prod_wages,salary_sheet.attn_bonus,salary_sheet.prod_bonus,
salary_sheet.ot_hours,salary_sheet.ot_rate,salary_sheet.ot_amount,salary_sheet.stamp_deduct,
salary_sheet.absent_deduction,salary_sheet.net_payable,
employee.employee_code,employee.employee_name,employee.designation_id,employee.employee_grade,
attendance_summery.working_days
from salary_sheet
left join employee 
on salary_sheet.employee_id = employee.employee_id
left join attendance_summery 
on salary_sheet.payment_period_id = attendance_summery.payment_period_id
where salary_sheet.employee_type_id = 9 and salary_sheet.payment_period_id = 41             
order by salary_sheet.supervisorwise_serial desc

第一个左连接采用工作表employee_type_id 9和payment_period_id 41 所有的工作表保留。在左连接的右侧侧,无论这些员工是否存在,所有行都会出现(这是左连接的行为)。所以他们来了,如果不存在则为空值。

第一步的结果是左连接上的表,对table attendance_summary执行相同的操作。

所以是的,当你无意中犯了错误时,左连接至少会有重复的效果。