gpt4 book ai didi

sql - Oracle 子查询没有看到来自外部 block 2 级别的变量

转载 作者:行者123 更新时间:2023-12-03 10:22:45 25 4
gpt4 key购买 nike

我想在一个查询中获得一个帖子和与该帖子相关的第一条评论。这是我在 PostgreSQL 中的做法:

SELECT p.post_id, 
(select * from
(select comment_body from comments where post_id = p.post_id
order by created_date asc) where rownum=1
) the_first_comment
FROM posts p

它工作正常。

但是,在 Oracle 中,我收到错误 ORA-00904 p.post_id: invalid identifier。

对于一个子选择,它似乎工作正常,但由于我需要使用 rownum(在 Oracle 中没有限制/偏移)这一事实,我无法获得只有一个的评论。

我在这里做错了什么?

最佳答案

不,Oracle不关联嵌套超过一层的子查询(MySQL 也不关联)。

这是一个众所周知的问题。

用这个:

SELECT  p.post_id, c.*
FROM posts
JOIN (
SELECT c.*, ROW_NUMBER() OVER (PARTITION BY post_id ORDER BY created_date ASC) AS rn
FROM comments c
) c
ON c.post_id = p.post_id
AND rn = 1

关于sql - Oracle 子查询没有看到来自外部 block 2 级别的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2048244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com