加入两个表来获取考勤和用户名mysql

时间:2016-04-16 04:38:14

标签: php mysql sql codeigniter left-join

我有两个表employee_info和出勤率:

CREATE TABLE IF NOT EXISTS `employee_info` (
  `emp_id` varchar(20) NOT NULL,
  `emp_name` varchar(30) NOT NULL,
  `emp_contact` varchar(30) NOT NULL,
  `com_address` varchar(30) NOT NULL,
  `per_address` varchar(30) NOT NULL,
  `com_phone` varchar(13) NOT NULL,
  `com_email` varchar(20) NOT NULL,
  `empid` int(20) NOT NULL,
  `emp_company` varchar(20) NOT NULL,
  `emp_branch` varchar(20) NOT NULL,
  `emp_dept` varchar(20) NOT NULL,
  `emp_designation` varchar(20) NOT NULL,
  `emp_salary` varchar(30) NOT NULL,
  `emp_type` varchar(10) NOT NULL,
  `last_updated` date NOT NULL,
  `active` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `attendance` (
`id` int(11) NOT NULL,
  `company` varchar(20) NOT NULL,
  `branch` varchar(55) NOT NULL,
  `dept` varchar(100) NOT NULL,
  `employee_id` varchar(255) NOT NULL,
  `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `status` varchar(12) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

我使用此查询获得总计现有和不计数:

select employee_id
  ,count(case when status =1  then 1 end) as absent_count
  ,count(case when status =2 then 1 end) as present_count
  ,count(distinct time) as Tot_count
from attendance where time between '2014-01-01' and '2016-04-12' 
group by employee_id

如何加入这两个表来获取emp_name ???

1 个答案:

答案 0 :(得分:0)

select employee_id,
     count(case when status =1 then 1 end) as absent_count,
     count(case when status =2 then 1 end) as present_count,
     count(distinct time) as Tot_count 
from attendance  
     join employee_info on attendance.employee_id = employee_info.id 
where time between '2014-01-01' and '2016-04-12' 
group by employee_id