I have a schema in Oracle-12c similar to a regular forum with accounts
, posts
, comments
. I am writing one request to get ...
- single user
- all user posts
- comments on each of these posts
- and the author of each comment.
The request is as follows:
select "accounts".*, "p".*, "c".*, "author".* from "accounts" cross apply ( select * from "posts" where "posts"."author_id" = "accounts"."id" ) "p" cross apply ( select * from "comments" where "comments"."post_id" = "p"."id" ) "c" left join "accounts" "author" on "author"."id" = "c"."author_id" where "accounts"."id" = 1
This query works as expected. I use CROSS APPLY
instead of the usual JOIN, because I will add OFFSET
and FETCH
for further pagination. However, the problem is that CROSS APPLY
omits posts that have no comments, which I don't want. I want to keep posts in the results, even if they have no comments.
So I tried changing CROSS APPLY
to OUTER APPLY
.
select "accounts".*, "p".*, "c".*, "author".* from "accounts" outer apply ( select * from "posts" where "posts"."author_id" = "accounts"."id" ) "p" outer apply ( select * from "comments" where "comments"."post_id" = "p"."id" ) "c" left join "accounts" "author" on "author"."id" = "c"."author_id" where "accounts"."id" = 1
But now I get this error:
ORA-00904: "p"."id": invalid identifier 00904. 00000 - "%s: invalid identifier" *Cause: *Action: Error at Line: 9 Column: 34
For some reason, my second OUTER APPLY
union complains that I refer to "p"."id"
the results of the first. But this is great when I used CROSS APPLY
.
What's happening? Why is there such a difference in behavior between them?
EDIT: OUTER APPLY
may not seem necessary in this basic example. This is distilled from a more complex scenario in which I must insist that OUTER APPLY
really necessary, but the details of this scenario are not related to the real question that I am asking - regarding this seemingly undocumented difference in behavior between CROSS
and OUTER
APPLY
.
EDIT:
Oracle Version: Database 12c Standard Version Release 12.1.0.2.0 - 64bit Production
Client: Oracle SQL Developer version 4.2.0.16.356
Server: uname -a
output - Linux ubuntu-1gb-sfo2-01 4.4.0-64-generic #85-Ubuntu SMP Mon Feb 20 11:50:30 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
DDL: link