MySQL加入子查询

时间:2013-08-02 17:41:29

标签: mysql join

我有三个表,我试图从两个表中获取信息,然后对第三个表执行计算,并在一个查询中显示所有结果。

(简化)表格是:

表:employee_work

employee_id name
1 Joe
2 Bob
3 Jane
4 Michelle

表:结转

employee_id days
1 5
2 10
3 3

表:timeoff

employee_id time_off_type days
1 Carryover 2
1 Leave 3
1 Carryover 1
2 Sick 4
2 Carryover 4
3 Leave 1
4 Sickness 4

我想要的结果是:

employee_id, carryover.days, timeoff.days
1 5 3
2 10 4
3 3 0

然而,当我运行查询时,虽然我在第1列和第2列中得到了正确的值,但我在第三列中为所有条目重复了相同的数字。

这是我的问题:

Select
  employee_work.employee_id,
  carryover.carryover,
  (SELECT SUM(days) FROM timeoff WHERE timeoff.time_off_type = 'Carryover' 
  AND timeoff.start_date>='2013-01-01') AS taken
From
  carryover Left Join
  employee_work On employee_work.employee_id = carryover.employee_id Left Join
  timeoff On employee_work.employee_id = timeoff.employee_id Left Join
Where
  carryover.carryover > 0
Group By
  employee_work.employee_id

我试图在子查询中进行分组,但后来我被告知“子查询返回多行” - 我如何确保子查询尊重连接,因此它一次只查看每个员工所以我得到了我想要的结果?

1 个答案:

答案 0 :(得分:1)

您的问题的答案是使用相关子查询。在这种情况下,您不需要提及timeoff表两次:

Select
  employee_work.employee_id,
  carryover.carryover,
  (SELECT SUM(days)
   FROM timeoff
   WHERE timeoff.time_off_type = 'Carryover' and
         timeoff.start_date>='2013-01-01' and
         timeoff.employee_id = employee_work.employee_id
  ) AS taken
From
  carryover Left Join
  employee_work On employee_work.employee_id = carryover.employee_id
Where
  carryover.carryover > 0
Group By
  employee_work.employee_id;

另一种结构是在from子句中为所有员工进行分组。您也可以删除employee_work表,因为它似乎没有被使用。 (您可以使用carryover.employee_id作为ID。)

Select co.employee_id, co.carryover, et.taken
From carryover c Left Join
     (SELECT employee_id, SUM(days) as taken
      FROM timeoff
      WHERE timeoff.time_off_type = 'Carryover' and
            timeoff.start_date>='2013-01-01'
     ) et
     on co.employee_id = et.employee_id
 Where c.carryover > 0;

我不认为group by是必要的。如果是,那么你应该在原始查询中有一个聚合函数。