如何在同一查询/语句中使用 SQL select 导致另一个子 select?

How to use SQL select results in another sub select in same query / statement?

这有点难以解释 - 希望它是一个简单的解决方案。我有一个 table,我正在做 select。

这是一般查询:

SELECT id, sub_id, name, inception_date, pc_code FROM investments;

这将拉取所有很棒的东西 - 但我需要使用从此 select 语句返回的 sub_id 字段数据重新查询 table 并拉入子 ID 的名称。这是我在伪代码中所追求的:

SELECT id, name, **sub_id**,
(SELECT name FROM investments where id = (sub_id from outer select statement)),
inception_date, pc_code
FROM investments;

sub_id 和 sub_id 名称只会查询相同的 table id 和名称。

我希望这是有道理的,感谢大家的帮助!

这是作品吗?

WITH cte as (SELECT id,  name FROM investments )
SELECT a.id, a.name, a.sub_id,  a.inception_date, a.pc_code , b.name
FROM investments a
INNER JOIN cte b on b.id  = a.sub_id ;

或更简单

SELECT a.id, a.name, a.sub_id,  a.inception_date, a.pc_code , b.name
FROM investments a
INNER JOIN investments b on b.id  = a.sub_id ;

看起来您不需要子选择,而是将相同的 table 与外部联接双重使用,试试这个并注意 table 中的两列使用 sub_id 如果没有匹配项,可以为 null。

SELECT a.id, a.name, b.id , b.name, a.inception_date, a.pc_code
FROM investments a 
LEFT OUTER JOIN investments b ON b.id = a.sub_id;