简体   繁体   English

从具有嵌套关系的一张表中获取数据

[英]Get data from one table with nested relations

I am new in DB and I have a table topics and in this table, I have a foreign key master_topic_id and this foreign key is related to the same table topics column id.我是数据库的新手,我有一个表主题,在这个表中,我有一个外键master_topic_id ,这个外键与同一个表主题列 id 相关。 Schema:架构:

CREATE TABLE public.topics (
id bigserial NOT NULL,
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
published_at timestamp NULL,
master_topic_id int8 NULL,
CONSTRAINT t_pkey PRIMARY KEY (id),
CONSTRAINT t_master_topic_id_fkey FOREIGN KEY (master_topic_id) REFERENCES topics(id
);

I write a query - SELECT * FROM topics WHERE id = 10. But if this record has master_topic_id I need to get data by master_topic_id too.我写了一个查询 - SELECT * FROM topics WHERE id = 10。但是如果这条记录有master_topic_id我也需要通过master_topic_id获取数据。 I tried to do it by using JOIN, but join just concat records, but I need to have data from master_topic_id as new row.我尝试使用 JOIN 来做到这一点,但只加入 concat 记录,但我需要将master_topic_id中的数据作为新行。 Any help?有什么帮助吗?

I think you are describing:我想你在描述:

select t.*
from topics t
where t.id = 10 or
      exists (select 1
              from topics t2
              where t2.master_topic_id = t.id and t2.id = 10
             );

However, you might just want:但是,您可能只想:

where 10 in (id, master_topic_id)

Use or in your where condition使用or在你的where条件下

SELECT * 
FROM topics 
WHERE id = 10 
or master_topic_id = 10

you can use union all as well你也可以使用union all

SELECT * 
FROM topics 
WHERE id = 10 

union all

SELECT * 
FROM topics 
WHERE master_topic_id = 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM