mysql 需要连接三个数据库表

wyyhbhjk  于 2023-01-20  发布在  Mysql
关注(0)|答案(1)|浏览(114)

我有以下三张表。

CREATE TABLE `attendance` (
    `attendance_id` bigint(100) NOT NULL AUTO_INCREMENT,
    `attendence_date` varchar(50) DEFAULT NULL,
    `status` int(11) DEFAULT NULL,
    `employee_id` bigint(20) DEFAULT NULL,
    PRIMARY KEY (`attendance_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
CREATE TABLE `employees` (
    `id` bigint(20) NOT NULL AUTO_INCREMENT,
    `active` tinyint(1) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=108 DEFAULT CHARSET=utf8mb4 COLLATE=latin1;
CREATE TABLE `ctc_master` (
    `id` bigint(20) NOT NULL AUTO_INCREMENT,
    `employee_id` bigint(20) DEFAULT NULL,
    `year` varchar(250) DEFAULT NULL,
    `ctc` decimal(14,2) DEFAULT NULL
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

数据如下
考勤表
| 考勤标识|出席日期|地位|雇员标识|
| - ------|- ------|- ------|- ------|
| 1个|2023年1月29日|1个|1个|
| 第二章|2023年1月30日|1个|1个|
| 三个|2023年1月29日|1个|第二章|
| 四个|2023年1月30日|无|第二章|
| 五个|2023年1月29日|1个|三个|
| 六个|2023年1月30日|无|三个|
| 七|2023年1月29日|1个|四个|
| 八个|2023年1月30日|1个|四个|
雇员表
| 身份证|主动|
| - ------|- ------|
| 1个|1个|
| 第二章|1个|
| 三个|1个|
ctc_主机
| 身份证|雇员标识|年份|反恐委员会|
| - ------|- ------|- ------|- ------|
| 1个|1个|二○二三|一百万|
| 第二章|第二章|二○二三|八十万|
| 三个|三个|二○二三|十五万元|
| 四个|1个|小行星2022|一百万|
| 五个|第二章|小行星2022|八十万|
| 六个|三个|小行星2022|十五万元|
尝试以下查询以获取时间段之间出勤状态= 1时的所有员工和计数。

select count(*) , employee_id from attendance atd where status = 1 and 
attendence_date between '2022-10-01'  and '2022-10-30' group by employee_id ;

我需要连接以上三个表来获取employee_id、ctc、考勤状态计数

select ctc.employee_id, ctc.ctc , ctc.year from  employees emp  
join ctc_master_tbl ctc on  emp.id = ctc.employee_id  
join attendance atd on emp.id = atd.employee_id 
and emp.id  = atd.employee_id and  emp.id = ctc.employee_id  where emp.active =1 and  
atd.attendence_date between '2022-01-28'  and '2022-01-31' ;

预期产出为

employee_id , year of the attendence_date ,count of status of each employee where status =1 , ctc.
ldfqzlk8

ldfqzlk81#

如果我理解正确的话,您需要在attendence和ctc_master之间的连接中添加年份,然后按选择列表中的非聚合字段分组-

select ctc.employee_id, ctc.ctc , ctc.year, SUM(status = 1) as present, SUM(status = 0) as absent
from  employees emp  
join ctc_master ctc
    on  emp.id = ctc.employee_id 
join attendance atd
    on emp.id = atd.employee_id
    and ctc.year = year(atd.attendence_date)
where emp.active = 1
and atd.attendence_date between '2022-01-28'  and '2022-01-31'
group by emp.id, ctc.year, ctc.ctc;

如果您在ctc_master(employee_id,year)上添加“missing”唯一索引,则在group by列表中将不再需要ctc.ctc

相关问题