【问题标题】:How to use SQL select results in another sub select in same query / statement?如何在同一查询/语句中的另一个子选择中使用 SQL 选择结果?
【发布时间】:2022-01-10 13:56:45
【问题描述】:

这有点难以解释 - 希望这是一个简单的解决方案。我有一张表,我正在对其进行选择。

这是一般查询:

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

这将提取所有很棒的东西 - 但我需要使用从该 select 语句返回的 sub_id 字段数据来重新查询表并提取子 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 名称只会在同一个表中查询 id 和 name。

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

【问题讨论】:

    标签: sql plsql


    【解决方案1】:

    这是工作吗?

    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 ;
    

    【讨论】:

    • 谢谢 - 很大的帮助!
    【解决方案2】:

    看起来您不需要子选择,而是通过外部连接双重使用同一个表,试试这个并注意表中使用 sub_id 的两列可以为空,以防不匹配。

    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;
    

    【讨论】:

    • 谢谢 - 很大的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2011-01-03
    • 1970-01-01
    • 2012-07-04
    • 2022-01-09
    • 2021-08-04
    • 2012-11-26
    相关资源
    最近更新 更多