以链的形式获取记录

时间:2013-08-30 04:06:40

标签: sql postgresql

我正在尝试创建一个SQL查询来以链的形式获取记录。

以下是一个例子:

如果A已经受到B邀请并且在接受了A链的邀请后 将开始。

在这个链中我想显示像

这样的记录
  • A受B
  • 邀请
  • B受C
  • 邀请
  • C受D
  • 邀请

你能帮我写一下这个问题吗?

这是结构

申请人表

id     Name   email
100   ABC  abc@test.com
101   PQR  pqr@test.com
102   XYZ  xyz@test.com
....... .......

Roommates table

id      email             created_by
1001    xyz@test.com      101
1002    pqr@test.com      100
............. .............

根据created_by字段,我们应该显示以下结果

结果应为 -

XYZ invited by PQR
PQR invited by ABC
..... ......

1 个答案:

答案 0 :(得分:1)

看起来您只需要加入即可:

select
    A.Name || ' invited by ' || C.Name
from Roommates as R
    inner join Applicants as A on A.id = R.applicant_id
    inner join Applicants as C on C.id = R.created_by

<强>更新

create or replace function get_chain(_id int)
returns table(data text)
as
$$
   with recursive cte as (
       select r.created_by, a.id as applicant_id
       from roommates as r
           inner join applicants as a on a.email = r.email
       where r.created_by = _id

       union all

       select r.created_by, a.id as applicant_id
       from roommates as r
           inner join applicants as a on a.email = r.email
           inner join cte as c on c.applicant_id = r.created_by
   )
   select
       A."Name" || ' invited by ' || R."Name"
   from cte as c
       inner join Applicants as A on A.id = c.applicant_id
       inner join Applicants as R on R.id = c.created_by
$$
language sql;

sql fiddle demo