我的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
为什么?
答案 0 :(得分: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
据推测,编写这样的查询会更自然(假设你真的想使用标量子查询),其中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(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.