简体   繁体   中英

why there is invalid identifier in this query?

I want to assign the result of count to a variable, so I can use it later in the query, here is my code:

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

the error: ORA-00904: "ALLINS": invalid identifier

This is your query:

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

Naughty, naughty. You cannot use a column alias defined in the select in a where clause. You also can't use aggregation function in the where clause, so the code doesn't make sense. What you want is a having clause:

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

Note: you almost never need select distinct when you have an aggregation query. And, distinct isn't a function so parenthesis are unnecessary.

Standard SQL disallows references to column aliases in a WHERE clause.

This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. Column_alias can be used in an ORDER BY clause, but it cannot be used in a WHERE, GROUP BY, or HAVING clause.

Documentation references:

http://dev.mysql.com/doc/refman/5.5/en/problems-with-alias.html

http://msdn.microsoft.com/en-us/library/ms173451.aspx

The execution for SQL is definitely not the same as Java or C, so often it trips up new programmers getting into the language.

More often than not, the database's order for understanding SQL instructions goes like this:

FROM -> WHERE -> GROUP BY -> ... -> SELECT

In order to do this properly you can't state that something is an alias in the SELECT clause, and expect it to work, because the program would most likely start from the FROM clause.

Also, from my experience, column aliases don't work with each other nicely when referencing each other in the SELECT clause.

My rather unfortunate solution would be to just not use aliases and type the whole thing out.

Also, you absolutely, positively, should not use an aggregate function in the WHERE clause. It must always be in the HAVING clause. You also need to use a GROUP BY clause if you don't want Oracle to complain about asking for the Artist. Also, since you are grouping by the Artist and the other function is an aggregate, you don't need to use DISTINCT.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM