Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 为什么此查询中存在无效标识符?_Sql_Oracle11g - Fatal编程技术网

Sql 为什么此查询中存在无效标识符?

Sql 为什么此查询中存在无效标识符?,sql,oracle11g,Sql,Oracle11g,我想将count的结果分配给一个变量,以便稍后在查询中使用,下面是我的代码: select distinct(Artist), count(distinct(Instrument)) as allins from performers where allins = (select count(distinct(x.Instrument)) from performers x) group by Artist; 错误:ORA-00904:ALLINS:in

我想将count的结果分配给一个变量,以便稍后在查询中使用,下面是我的代码:

select distinct(Artist), count(distinct(Instrument)) as allins 
from performers 
where allins = (select count(distinct(x.Instrument)) 
                from performers x) 
group by Artist;

错误:ORA-00904:ALLINS:invalid identifier

标准SQL不允许在WHERE子句中引用列别名

施加此限制是因为在计算WHERE子句时,可能尚未确定列值。 列别名可以在ORDER BY子句中使用,但不能在WHERE、GROUP BY或HAVING子句中使用

文件参考:

这是您的查询:

select distinct(Artist), count(distinct(Instrument)) as allins 
from performers
where allins = (select count(distinct(x.Instrument)) from performers x)
group by Artist;
淘气,淘气。不能使用在where子句中选择中定义的列别名。您也不能在where子句中使用聚合函数,因此代码没有意义。您需要的是having子句:


注意:当您有一个聚合查询时,几乎不需要select distinct。而且,distinct不是一个函数,因此不需要括号。

SQL的执行肯定不同于Java或C,因此它经常会绊倒新程序员进入该语言

通常,数据库理解SQL指令的顺序如下:

从->位置->分组依据->…->挑选

为了正确地执行此操作,您不能在SELECT子句中声明某个内容是别名,并期望它工作,因为程序很可能从from子句开始

另外,根据我的经验,在SELECT子句中引用列别名时,列别名之间的相互作用不好

我相当不幸的解决办法是不使用别名,而是把整个事情都打出来

此外,您绝对不应该在WHERE子句中使用聚合函数。它必须始终在HAVING子句中。如果您不想让Oracle抱怨找艺术家,还需要使用GROUPBY子句。此外,由于您是按艺术家分组的,而另一个函数是聚合函数,因此不需要使用DISTINCT。

可能重复的
select Artist, count(distinct(Instrument)) as allins 
from performers
group by Artist
having count(distinct Instrument) = (select count(distinct x.Instrument) from performers x)