28

我想在一个查询中获取一个帖子以及与该帖子关联的第一条评论。这是我在 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 中没有限制/偏移),我无法获得只有一个的评论。

我在这里做错了什么?

4

2 回答 2

50

不,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
于 2010-01-12T10:43:02.323 回答
3

如果您需要独立于平台的 SQL,这将起作用:

SELECT p.post_id
     , c.comment_body
  FROM posts p
     , comments c
 WHERE p.post_id = c.post_id
   AND c.created_date IN
       ( SELECT MIN(c2.created_date)
           FROM comments c2
          WHERE c2.post_id = p.post_id
        );

但它假设 (post_id, created_date) 是评论的主键。如果不是,您将收到多行帖子,其中包含具有相同 created_date 的评论。

此外,它可能比 Quassnoi 提供的使用分析的解决方案要慢。

于 2010-01-12T15:18:58.023 回答