从两个表中选择结果(Mysql)

时间:2015-12-22 12:58:55

标签: mysql sql

我有2个表,一个是 employee_job 表,另一个是 employee_exit 表,其中的映射数据为 employee_id

employee_job

id |  employee_id | date_of_joining | date_of_rehire
-----------------------------------------------------------------
1  | 1            | 2015-01-01      | 2015-07-01
2  | 2            | 2014-02-01      | 2014-12-01 

employee_exit

id |  employee_id | date_of_termination | date_of_rehire
-----------------------------------------------------------------
1  | 1            | 2015-02-15          | 2015-03-01
2  | 1            | 2015-03-31          | 2015-05-01
3  | 1            | 2015-05-31          | 2015-07-01 
4  | 2            | 2014-06-12          | 2014-07-01 
5  | 2            | 2014-10-31          | 2014-12-01
6  | 2            | 2015-02-30          | (NULL)

仅重新雇用员工时,只有最新的 date_of_rehire 会出现在 employee_job 表中。如果在重新搜索后终止,则 employee_job 表中将存在 date_of_rehire

结果我需要以下输出: -

employee_id  |  date_of_hire | date_of_termination
-----------------------------------------------------------------
1            | 2015-01-01    | 2015-02-15 
1            | 2015-03-01    | 2015-03-31
1            | 2015-05-01    | 2015-05-31
1            | 2015-07-01    | (NULL) 
2            | 2014-02-01    | 2014-06-12 
2            | 2014-07-01    | 2014-10-31
2            | 2014-12-01    | 2015-02-30

如果员工多次被雇主雇用,那么它是 date_of_joining date_of_termination 之间的第一个招聘期,然后是 date_of_rehire 之后的 date_of_termination

如果员工只被雇用一次,那么它在 date_of_joining date_of_termination 之间的招聘期间。

2 个答案:

答案 0 :(得分:1)

从这个任务的角度来看,两个表格中的date_of_joiningdate_of_rehire之间没有区别,所以我们只需要Union全部,并补充最近的date_of_termination

Select
  Hire.employee_id,
  Hire.date_of_hire,
  (
    Select Min(date_of_termination)
    From employee_exit
    Where employee_exit.employee_id = Hire.employee_id
      AND employee_exit.date_of_termination > Hire.date_of_hire
  ) As date_of_termination
From (
    Select       employee_id, date_of_joining As date_of_hire From employee_job
  /*Optional, in case employee_job has date_of_rehire not in employee_exit     */
  /*Union Select employee_id, date_of_rehire                  From employee_job*/
    Union Select employee_id, date_of_rehire                  From employee_exit
  ) Hire
Order By
  Hire.employee_id,
  Hire.date_of_hire

如果在数据库中没有准确记录任何日期,则可能会出现模糊结果。

答案 1 :(得分:0)

我的主要答案是重做数据库,这样你就不必对一个相当直接的操作进行复杂的查询。如果这不是一个选项,那么下面我给出了一个快速回答。可能有一个问题,但它应该让你走上正确的轨道

我会使用联盟来结合您想要的两个查询的结果(第一个任期和所有其他就业条款):

    (SELECT employee_job.employee_id, employee_job.date_of_joining as date_of_hire, employee_exit.date_of_termination 
     FROM employee_job       
     JOIN employee_exit
     ON employee_job.employee_id = employee_exit.employee_id
     UNION
     SELECT employee_job.employee_id, employee_exit.date_of_rehire as date of hire, employee_exit.date of termination 
    FROM employee_job       
     JOIN employee_exit
     ON employee_job.id = employee_exit.id)
     ORDER BY employee.id

这可能会给你重复,如果是这样,那么需要仔细放置where子句:D