我有两张桌子
团队表
id name
1 A
2 B
3 B1
4 B2
Team_mapping表
id team_id parentid
1 1 0
2 2 0
3 3 2
4 4 2
显示应该是这样的
Team Name Parent Name
A -
B -
B1 B
B2 B
请帮我写一个与上面显示相同的SQL查询输出
答案 0 :(得分:1)
这是一个坏主意。有两种方法可以做到这一点,
ltree
使用分层单表最适合您。这是一个次要的重组,但它更具语义性。
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' );
有关此递归查询的示例..
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)
这允许任意深层次。
INSERT INTO teams (id, parent, name) VALUES
( 5, 4, 'Deep' );
运行与上面相同的查询,
id | name | parent
----+------+--------
1 | A | {}
2 | B | {}
3 | B1 | {B}
4 | B2 | {B}
5 | Deep | {B,B2}
(5 rows)
答案 1 :(得分:0)
一种方法是使用left join
,并加入teams
两次:
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
然后您可以在select
语句中使用子查询:
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
编辑:上一个第一个答案的join
不正确,如果表left join
中没有parentid,则应为teams
。此外,对于null
,请使用coalesce
转换为-
。
Demo。