Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

nested subquery / invalid identifier

687216Nov 24 2009 — edited Dec 7 2009
I need to create a quite complex SQL report, and I've run into the following problem. Imagine two simple tables - say table_a and table_b:
create table table_a (id integer, primary key (id));

create table table_b (id integer, a_id integer references table_a(id), primary key (id)); 
Say I need to run a query that (a) selects all the rows from table_a, and (b) counts all related rows from table_b. That's something like this
SELECT a.*,
    (SELECT COUNT(*) FROM table_b WHERE a_id = a.id) AS cnt
FROM table_a a
This works fine, but I need to do much more complex operations on table_b (CONNECT BY, etc.) so I need to nest the subselects and move the "a_id = a.id" condition "deeper" - something like this:
SELECT a.*,
    (SELECT COUNT(*) FROM
        (SELECT * FROM table_b WHERE a_id = a.id)
    ) AS cnt
FROM table_a a
Again - this is just a simplified example, I need to perform much more complex processing.

But as it turns out this returns "ORA-00904: invalid identifier" exception, as Oracle suddenly does not know the "a.id" in the inner-most query. How to solve this? How to convince Oracle to use the value from the outer query?

Edited by: TomasVondra on 24.11.2009 3:26
This post has been answered by Karthick2003 on Nov 24 2009
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 4 2010
Added on Nov 24 2009
14 comments
14,532 views