假设我有三个表:
employees
,具有列id
和name
salaries
,带有列employee_id
,salary
,date
underlings
,带有列employee_id
,number_of_underlings
,date
我想连接表,以便对于每个salaries
条目,都有一行带有salary
值的行,与该行的name
关联的employee_id
以及number_of_underlings
值,该行的date
项最近在date
的{{1}}之前(即,给定员工应具有的下标数量当时他们有给定的工资)。
例如,假设以下行出现在描述的表中:
salaries
然后,结果联接将具有行:
id | name employee_id | salary | date employee_id | number_of_underlings | date
---+------- -------------+---------+------------ -------------+----------------------+------------
13 | Sally 13 | 90000 | 2017-11-29 13 | 0 | 2017-05-13
13 | 95000 | 2018-01-01 13 | 6 | 2018-02-20
13 | 120000 | 2018-03-01
当然,联接 name | salary | number_of_underlings | date
-------+---------+----------------------+------------
Sally | 90000 | 0 | 2017-11-29
Sally | 95000 | 0 | 2018-01-01
Sally | 120000 | 6 | 2018-03-01
和employees
表是微不足道的,但是salaries
表又如何呢?
答案 0 :(得分:1)
一种方法是使用相关子查询:
SELECT
e.name,
s.salary,
(SELECT u.number_of_underlings FROM underlings u
WHERE e.id = u.employee_id AND s.date >= u.date
ORDER BY u.date DESC LIMIT 1) number_of_underlings,
s.date
FROM employees e
INNER JOIN salaries s
ON e.id = s.employee_id