oracle从2表中选择限制从1表和另一个表

时间:2013-05-21 14:25:11

标签: sql oracle

我有书和收件人表。我想按收件人表的membershipdate列选择最多20行。在我得到它之后,我想通过book table的id列来订购它。我写了那个sql。有没有办法用更少的代码来做到这一点?

SELECT  *
FROM    ( SELECT    *
          FROM      ( SELECT    b.*
                      FROM      book b
                                JOIN recipient r ON r.id = b.recipient_id
                      WHERE     b.bookno = 115
                      ORDER BY  r.membershipdate DESC
                    )
          WHERE     ROWNUM <= 20
        )
ORDER BY ID DESC

3 个答案:

答案 0 :(得分:3)

您可以移除一层select

SELECT *
FROM (
    SELECT    b.*
    FROM      book b
    JOIN recipient r ON r.id = b.recipient_id
    WHERE     b.bookno = 115
    ORDER BY  r.membershipdate DESC
)
WHERE ROWNUM <= 20
ORDER BY id DESC;

选择b.*通常不是一个好主意,但最好指定您真正想要的列,即使您真的想要它们 - 确保按照您期望的顺序获取它们。 / p>

您还可以查看row_number() analytic function in place of rownum,但这会为您提供更多代码 - 而不是它应该重要,查询的有效性和效率更重要的是它的长度。

答案 1 :(得分:0)

这不起作用吗?

                  SELECT * FROM
                   (SELECT    b.*
                    FROM      book b
                            JOIN recipient r ON r.id = b.recipient_id
                    WHERE     b.bookno = 115 ORDER BY  r.membershipdate DESC
                   ) WHERE ROWNUM <= 20
                  ORDER BY ID DESC

答案 2 :(得分:0)

在oracle中,您可以使用ROW_NUMBER()函数来减少代码 -

您甚至可以混合您的订单栏。

select * from (
select b.*,row_number() over (order by r.membershipdate desc) cnt
from book b
JOIN recipient r ON r.id = b.recipient_id
WHERE b.bookno = 115
order by cnt,b.id desc
) where cnt<=20;