1

我正在尝试进行 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
..... ......
4

1 回答 1

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

于 2013-08-30T04:58:47.637 回答