You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于SQL的关系建模:PostgreSQL双角色关联查询问题

PostgreSQL 关系主体与关系查询实现

1. 查询自身作为「employer」对应的「employee」关联主体

假设你的PersonID为my_person_id(实际使用时替换为具体数值),可通过自连接RelatedParty表匹配同一关系下的双角色主体:

SELECT rp_emp.PersonID AS employee_id
FROM RelatedParty rp_employer
JOIN RelatedParty rp_emp 
  ON rp_employer.RelationshipID = rp_emp.RelationshipID
WHERE rp_employer.PersonID = my_person_id
  AND rp_employer.Role = 'employer'
  AND rp_emp.Role = 'employee';

逻辑说明

  • 自连接关联同一RelationshipID下的两条记录,锁定同一关系内的两个主体
  • 筛选自身为employer的记录,匹配同关系中角色为employee的关联主体

2. 查询自身作为「employer」、他人为「employee」的关系详情

关联Relationship表获取关系状态等完整信息,基于自连接筛选目标关系:

SELECT r.ID AS relationship_id, r.Status
FROM RelatedParty rp_employer
JOIN RelatedParty rp_emp 
  ON rp_employer.RelationshipID = rp_emp.RelationshipID
JOIN Relationship r 
  ON rp_employer.RelationshipID = r.ID
WHERE rp_employer.PersonID = my_person_id
  AND rp_employer.Role = 'employer'
  AND rp_emp.Role = 'employee';

逻辑说明

  • 先通过自连接筛选符合角色组合的关系ID
  • 关联Relationship表,获取该关系的状态等核心信息

内容的提问来源于stack exchange,提问作者Scott Deerwester

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 21:04:55