i have two tables
Teams table
id name
1 A
2 B
3 B1
4 B2
Team_mapping table
id team_id parentid
1 1 0
2 2 0
3 3 2
4 4 2
display should be like this
Team Name Parent Name
A -
B -
B1 B
B2 B
Please help me to write a sql query output same as above display
This is a bad idea. There are two ways to do this,
ltreeUsing the hierarchical single table is the best fit for you. It's a minor re-organization but it's much more semantic.
CREATE TABLE teams (
id serial PRIMARY KEY,
parent int REFERENCES teams,
name text
);
INSERT INTO teams (id, parent, name) VALUES
( 1, null, 'A' ),
( 2, null, 'B' ),
( 3, 2, 'B1' ),
( 4, 2, 'B2' );
For an example of a recursive query for this..
WITH RECURSIVE t(id,name,parent) AS (
SELECT t1.id, t1.name, ARRAY[]::text[]
FROM teams AS t1
WHERE parent IS NULL
UNION ALL
SELECT t2.id, t2.name, t1.parent || ARRAY[t1.name]
FROM t AS t1
JOIN teams AS t2
ON t2.parent = t1.id
)
SELECT *
FROM t;
id | name | parent
----+------+--------
1 | A | {}
2 | B | {}
3 | B1 | {B}
4 | B2 | {B}
(4 rows)
This allows arbitrarily deep hierarchy.
INSERT INTO teams (id, parent, name) VALUES
( 5, 4, 'Deep' );
Running the same query as above,
id | name | parent
----+------+--------
1 | A | {}
2 | B | {}
3 | B1 | {B}
4 | B2 | {B}
5 | Deep | {B,B2}
(5 rows)
One way is use left join, and join teams twice:
select
coalesce(t1.name, '-') "Team Name", coalesce(t2.name, '-') "Parent Name"
from team_mapping tm
left join teams t1 on tm.team_id = t1.id
left join teams t2 on tm.parentid = t2.id
then you can use subquery in select statement:
select
coalesce((select t.name from teams t where t.id = tm.team_id), '-') "Team Name",
coalesce((select t.name from teams t where t.id = tm.parentid), '-') "Parent Name"
from team_mapping tm
Edit: Previous first answer's join is incorrect, it should be left join in case of there is no parentid in table teams. Besides, for null s, use coalesce to convert to -.
Demo in sqlfiddle.