我有以下表结构
表hour_rate
CREATE TABLE `hour_rate` (
`hour_rate_id` int(11) NOT NULL AUTO_INCREMENT,
`hour_rate` decimal(8,2) NOT NULL,
`from_date` date NOT NULL,
`employee_id` int(11) NOT NULL,
PRIMARY KEY (`hour_rate_id`),
UNIQUE KEY `idx-unique-hour_rate-from_date-employee_id`
(`from_date`,`employee_id`),
KEY `idx-hour_rate-employee_id` (`employee_id`),
CONSTRAINT `fk-hour_rate-employee_id` FOREIGN KEY (`employee_id`)
REFERENCES `employee` (`employee_id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB;
表employee_work
CREATE TABLE `employee_work` (
`employee_work_id` int(11) NOT NULL AUTO_INCREMENT,
`project_id` int(11) NOT NULL,
`employee_id` int(11) NOT NULL,
`date` date NOT NULL,
`hours` int(11) NOT NULL,
PRIMARY KEY (`employee_work_id`),
UNIQUE KEY `idx-unique-employee_work-employee_id-date`
(`employee_id`,`date`),
KEY `idx-employee_work-employee_id` (`employee_id`),
CONSTRAINT `fk-employee_work-employee_id` FOREIGN KEY (`employee_id`)
REFERENCES `employee` (`employee_id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB;
表hour_rate
包含有关员工及其小时费率(hour_rate
)的记录,从日期开始(from_date
)
表employee_work
包含员工每天工作时间的记录
我想根据employee_work
和hour_rate
从date
选择具有适当小时费率的所有记录from_date
,以便我可以计算员工的付款({{ 1}} * hour_rate
)
例如,我有以下记录
在hours
hour_rate
并在+-----------+------------+-------------+
| hour_rate | from_date | employee_id |
+-----------+------------+-------------+
| 11.00 | 2018-01-10 | 1 |
| 12.00 | 2018-01-14 | 1 |
| 13.00 | 2018-01-18 | 1 |
| 5.00 | 2018-01-01 | 1 |
| 10.00 | 2018-01-15 | 2 |
+-----------+------------+-------------+
employee_work
我希望产生以下结果
+-------------+------------+-------+
| employee_id | date | hours |
+-------------+------------+-------+
| 1 | 2018-01-01 | 8 |
| 1 | 2018-01-02 | 8 |
| 1 | 2018-01-03 | 8 |
| 1 | 2018-01-04 | 8 |
| 1 | 2018-01-05 | 8 |
| 1 | 2018-01-08 | 8 |
| 1 | 2018-01-09 | 8 |
| 1 | 2018-01-10 | 8 |
| 1 | 2018-01-11 | 8 |
| 1 | 2018-01-12 | 8 |
| 1 | 2018-01-15 | 8 |
| 1 | 2018-01-16 | 8 |
| 1 | 2018-01-17 | 8 |
| 1 | 2018-01-18 | 8 |
| 1 | 2018-01-19 | 8 |
+-------------+------------+-------+
答案 0 :(得分:1)
一种方法使用相关子查询来获取速率:
select ew.*,
(ew.hours *
(select hr.hour_rate
from hour_rate hr
where hr.employee_id = ew.employee_id and
hr.from_date >= ew.date
order by hr.from_date
limit 1
)
) as daily_pay
from employee_work ew;
答案 1 :(得分:0)
您可以使用带2个表的select来完成此操作。您的数据示例如下:
select ew.employee_id, ew.date, ew.hours, hr.employee_id, hr.from_date (hr.hour_rate * ew.hours) as payment
from employee_work ew, hour_rate hr
where ew.employee_id = hr.employee_id