我需要根据不同的参数选择记录-如果一个记录丢失,那么一个默认值。
table在这里
absence_type
+------+--------+
|id | value |
+------+--------+
|1 | null |
|2 | null |
|3 | 20 |
|4 | null |
|5 | null |
|6 | null |
|7 | null |
|8 | null |
|9 | null |
+------+--------+
absences
+-------+-------------+-------------+----------------+------------+
|id | absenceType | employeeId | totalDuration | startDate |
+-------+-------------+-------------+----------------+------------+
|145 | 9 | 112 | 1 | 2023-01-13 |
|146 | 5 | 406 | 1 | 2023-11-15 |
+-------+-------------+-------------+----------------+------------+
absence_balance
+-------+-------------+-------------+----------------+-------------+
|id | absenceType | employeeId | entitlement | periodYear |
+-------+-------------+-------------+----------------+-------------+
|13 | 1 | 112 | 10 | 2022 |
|53 | 1 | 112 | 12 | 2023 |
|54 | 2 | 406 | 5 | 2023 |
+-------+-------------+-------------+----------------+-------------+
字符串
该请求将有一个员工ID,期间年份和一组允许的类型ID,比如'1,2,3,4,9'。
最后,我需要在该periodYear内拥有所有缺勤类型,如果缺勤或余额中缺少特定类型,我仍然需要显示该类型的默认值(absence_type -> value as defaultValue)。因此查询返回:
+--------+-----------+------------+-------------+--------------+---------------+
| typeId | absenceId | employeeId | entitlement | defaultValue | totalDuration |
+--------+-----------+------------+-------------+--------------+---------------+
| 1 | null | 112 | 12 | 20 | 0 |
| 2 | null | 112 | null | null | 0 |
| 3 | null | 112 | null | null | 0 |
| 4 | null | 112 | null | null | 0 |
| 9 | 145 | 112 | null | null | 1 |
+--------+-----------+------------+-------------+--------------+---------------+
型
看起来很简单,但是我得到的查询只返回一行,这行在absences
表中有一条记录(最后一条)。
select
`t`.`id` as `typeId`,
`a`.`id` as `absenceId`,
`a`.`employeeId`,
`b`.`entitlement`,
`t`.`value` as `defaultValue`,
`a`.`totalDuration`
from `absence_type` as `t`
left join `absences` as `a` on `a`.`absenceTypeId` = `t`.`id`
left join `absence_balance` as `b` on `b`.`employeeId` = `a`.`employeeId`
where (`a`.`employeeId` = 112 or `a`.`employeeId` is null)
and (`b`.`periodYear` = 2023 or `b`.`periodYear` is null)
and (`a`.`startDate` between '2023-01-01' and '2023-12-31' or `a`.`startDate` is null)
and `t`.`id` in (1,2,3,4,9)
group by `a`.`id`
型
1条答案
按热度按时间rqenqsqc1#
根据@Barmar的建议,这里是一个修改后的查询,它将条件移动到连接条件中:
字符串
当我运行它时,它几乎给出了所需的结果集:
型
不同之处在于
defaultValue
--我认为这里正确地显示了类型3。