子 + 父参考 SQL

Child + Parent reference SQL(子 + 父参考 SQL)
本文介绍了子 + 父参考 SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于子 + 父参考 SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)