[英]PostgreSQL: Sub-Query on one table
My table looks (simplified) like this:我的表看起来(简化)是这样的:
ID, File, Subst_ID
1, "AAA"
2, "BBB", 3
3, "CCC"
It records filenames "File";它记录文件名“文件”; sometimes, a file (here BBB) is replaced by a newer one (here CCC". First show all records, that have been replaced:有时,文件(此处为 BBB)会被更新的文件(此处为 CCC”)替换。首先显示已被替换的所有记录:
SELECT ID, File, Subst_ID FROM Table WHERE Subst_ID IS NOT NULL;
OK, brings up line 2. Now I need to add a subquery column QQ, which shows the File of the substitute record, eg should bring:好的,出现第2行。现在我需要添加一个子查询列QQ,它显示了替代记录的文件,例如应该带来:
2, "BBB", 3, "CCC"
. . My approach does not work:我的方法不起作用:
SELECT ID, File, Subst_ID, (SELECT File FROM Table WHERE Subst-ID = ID) AS QQ FROM Table WHERE Subst_ID IS NOT NULL;
Where is my mistake?我的错误在哪里? Thank you!谢谢!
I think you want a self-join:我认为你想要一个自我加入:
select t1.*, t2.file as subst_file
from mytable t1
inner join mytable t2 on t2.id = t1.subst_id
This is query you wanted to write - I find that is less neat, because it needs a where
clause, while the above does not:这是您想要编写的查询 - 我发现它不太整洁,因为它需要一个where
子句,而上面的则不需要:
select t1.*,
(select t2.file from mytable t2 where t2.id = t1.subst_id) as subst_file
from mytable t1
where t1.subst_id is not null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.