开发者

postgres getting data where two column references same parent id

There are 3 table in postgres database

CREATE TABLE tab_name
(
  name_id 开发者_StackOverflow中文版integer NOT NULL,
  cust_name character varying NOT NULL, -- contains names like david,jones,athur
  CONSTRAINT tab_name_pkey PRIMARY KEY (name_id)
)

CREATE TABLE tab_rel
(
  rel_id integer NOT NULL,
  rel_desc character varying NOT NULL,-- contains relation description father son, sister brother
  CONSTRAINT tab_rel_pkey PRIMARY KEY (rel_id)
)

CREATE TABLE tab_rel_map
(
  rel_id integer NOT NULL,
  name_id1 integer NOT NULL,
  name_id2 integer NOT NULL,
  CONSTRAINT tab_rel_map_name_id1_fkey FOREIGN KEY (name_id1)
      REFERENCES tab_name (name_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT tab_rel_map_name_id2_fkey FOREIGN KEY (name_id2)
      REFERENCES tab_name (name_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT tab_rel_map_rel_id_fkey FOREIGN KEY (rel_id)
      REFERENCES tab_rel (rel_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

I am trying to write function which take rel_id as input and should output cust_name respect to name_id1 and name_id2. Because both name_id1 and name_id2 references to same parent id I am not able to get respective name.

rel_id | relation     | cust_name1 | cust_name2
------------------------------------------------
1      | Father son   | David      | Jones


You need to join to the same table twice - here's how you do that using aliases:

select 
    rm.rel_id,
    r.rel_desc as relation,
    n1.cust_name as cust_name1,
    n2.cust_name as cust_name2
from tab_rel_map rm
join tab_rel r on r.id = rm.rel_id
left join tab_name n1 on n1.name_id = rm.name_id1
left join tab_name n2 on n2.name_id = rm.name_id2
where rm.rel_id = 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜