0

我的oracle版本是10.2。当标量子查询具有聚合操作时,这很奇怪。我的表名为 t_test 看起来像这样;

t_id    t_name
 1       1
 2       1
 3       2
 4       2
 5       3
 6       3      

查询字符串看起来像这样;

select t1.t_id,
       (select count(t_name)
         from (select t2.t_name 
                 from t_test t2 
                 where t2.t_id=t1.t_id 
                 group by t2.t_name)) a
from t_test t1

这个查询的结果是,

t_id  a
 1    3
 2    3
 3    3
 4    3
 5    3
 6    3

这很奇怪,以 t1.t_id=1 为例,

select count(t_name)
 from (select t2.t_name 
         from t_test t2 
         where t2.t_id=1
         group by t2.t_name)

结果是 1,不知何故,“where”运算符不起作用,结果与我这样查询的结果完全相同:

select t1.t_id,
       (select count(t_name)
         from (select t2.t_name 
                 from t_test t2 
                 group by t2.t_name)) a
from t_test t1

为什么?

4

1 回答 1

0

您可以从 SQL*Plus 中发布一个剪切和粘贴来准确显示您正在运行的查询吗?您发布的查询似乎无效 - 别名t1在您引用它的子查询中无效。这让我怀疑您正在简化问题以在此处发布,但您不小心遗漏了一些重要的东西。

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select 1 id, 1 name from dual union all
  3    select 2,1 from dual union all
  4    select 3,2 from dual union all
  5    select 4,2 from dual union all
  6    select 5,3 from dual union all
  7    select 6,3 from dual
  8  )
  9  select t1.id
 10        ,(select count(b.name)
 11            from (select t2.name
 12                    from x t2
 13                   where t2.id = t1.id
 14                   group by t2.name) b) a
 15*   from x t1
SQL> /
                 where t2.id = t1.id
                               *
ERROR at line 13:
ORA-00904: "T1"."ID": invalid identifier

据推测,这样编写查询会更自然(假设您真的想使用标量子查询) wheret1将是标量子查询中的有效别名。

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select 1 id, 1 name from dual union all
  3    select 2,1 from dual union all
  4    select 3,2 from dual union all
  5    select 4,2 from dual union all
  6    select 5,3 from dual union all
  7    select 6,3 from dual
  8  )
  9  select t1.id
 10        ,(select count(t2.name)
 11            from x t2
 12           where t2.id = t1.id) cnt
 13*   from x t1
SQL> /

        ID        CNT
---------- ----------
         1          1
         2          1
         3          1
         4          1
         5          1
         6          1

6 rows selected.
于 2012-04-09T14:31:16.097 回答