繁体   English   中英

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

[英]Get data from one table with nested relations

我是数据库的新手,我有一个表主题,在这个表中,我有一个外键master_topic_id ,这个外键与同一个表主题列 id 相关。 架构:

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
);

我写了一个查询 - SELECT * FROM topics WHERE id = 10。但是如果这条记录有master_topic_id我也需要通过master_topic_id获取数据。 我尝试使用 JOIN 来做到这一点,但只加入 concat 记录,但我需要将master_topic_id中的数据作为新行。 有什么帮助吗?

我想你在描述:

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
             );

但是,您可能只想:

where 10 in (id, master_topic_id)

使用or在你的where条件下

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

你也可以使用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