子 + 父参考 SQL

2021-12-30 00:00:00 sql oracle11g oracle

我正在尝试编写一个查询来显示项目的名称和父项目的名称,但到目前为止还没有正确的方法.

I am trying to write a query to display the name of the project and the name of the parent project, but haven't come with the proper way so far.

CREATE TABLE project
(p_id NUMBER(6),
project_name VARCHAR2(30),
client_id NUMBER(6),
mgr_id NUMBER(6),
parent_p_id NUMBER(6),
CONSTRAINT project_pid_pk PRIMARY KEY (p_id),
CONSTRAINT project_client_id_fk FOREIGN KEY (client_id) REFERENCES client(client_id),
CONSTRAINT project_mgr_id_fk FOREIGN KEY (mgr_id) REFERENCES consultant(c_id));

ALTER TABLE project
ADD CONSTRAINT project_parent_pid_fk FOREIGN KEY (parent_p_id) REFERENCES project(p_id);

通过使用:

SELECT project.p_id, project.project_name, project.parent_p_id
FROM project
WHERE project.parent_p_id IS NOT NULL;

我可以获得大部分信息,但我不知道如何将project.parent_p_id链接到project.project_name

I can get most of the information, but I don't know how to link the project.parent_p_id to the project.project_name

有人帮我吗?!

提前致谢:-)

推荐答案

你需要一个自联接,像这样将 PROJECT 表联接到自身

You need a self join, joining the PROJECT table to itself like this

SELECT p.p_id, 
       p.project_name, 
       p.parent_p_id, 
       pp.project_name as parent_project
FROM project p
     inner join project pp
     on p.parent_p_id = pp.p_id;

如果您想包含没有父项目的项目,则联接将是左外联接.

If you want to include projects which don't have a parent project then the join would be a LEFT OUTER JOIN.

相关文章