单个SQL SELECT查询,用于一对多关系

时间:2016-12-02 13:54:45

标签: sql postgresql one-to-many

如果没有例子,这个问题很难解释。

我有2个表,公司员工,他们有一对多的关系,一个公司可以参加很多员工。

这里显示最简单的表结构

Company
| id | name |

Employee
| id | name | company_id | join_date |

现在的问题是:

我如何选择前2名员工并将他们的加入日期显示为公司表中的列?

所以结果看起来像这样

| id |  company_name |  first_employee_join_at |  second_employee_join_at |

1 个答案:

答案 0 :(得分:2)

假设company_id表中有一个外键列employee

with emps as (
  select id, name, company_id, 
         row_number() over (partition by company_id order by join_date) as rn
  from employee
)
select c.id, c.name as company_name, 
       e1.join_date as first_employee_join_at, 
       e2.join_date as second_employee_join_at
from company c
  left join emps e1 on e1.company_id = c.id and e1.rn = 1
  left join emps e2 on e2.company_id = c.id and e2.rn = 2;

但这并不是非常有效。稍微高效的版本将使用条件聚合:

with emps as (
  select id, name, company_id, 
         row_number() over (partition by company_id order by join_date) as rn
  from employee
)
select c.id, c.name as company_name, 
       max(e.join_date) filter (where rn = 1) as first_employee_join_at, 
       max(e.join_date) filter (where rn = 2) as second_employee_join_at
from company c
  join emps e on e.company_id = c.id and e.rn in (1,2)
group by c.id, c.name;