没有别名的相关查询如何工作?

时间:2019-04-24 12:02:30

标签: sql oracle

以下代码返回结果,过程中没有错误。但是,变量b在视图nob中不存在。

WITH basetbl AS (
    SELECT
        1 AS a,
        2 AS b,
        1 AS c
    FROM
        dual
    UNION ALL
    SELECT
        2 AS a,
        3 AS b,
        0 AS c
    FROM
        dual
),nob AS (
    SELECT a, c
    FROM basetbl
) 
SELECT *
FROM basetbl
WHERE b IN (SELECT b FROM nob WHERE c = 1);

返回:

"A"  "B"  "C"                           
 1    2    1                           
 2    3    0                           

1 个答案:

答案 0 :(得分:1)

这是您的查询:

SELECT *
FROM basetbl
WHERE b IN (SELECT b FROM nob WHERE c = 1);

首先,您应该始终限定列名,因此查询应更像这样:

SELECT bt.*
FROM basetbl bt
WHERE bt.b IN (SELECT n.b FROM nob n WHERE n.c = 1);

那么你会得到一个错误。

相反,Oracle应用其默认范围规则(与所有SQL数据库的范围规则相似)。因此,当在b中找不到nob时,它将在外部查询中查找。该查询被解释为:

SELECT bt.*
FROM basetbl bt
WHERE bt.b IN (SELECT bt.b FROM nob n WHERE n.c = 1);