最大id日期:sql/oracle优化

发布于 2024-08-18 12:38:46 字数 140 浏览 1 评论 0原文

有什么更优雅的方法可以做到这一点:

select date from table where id in (
  select max(id) from table);

当然有更好的方法......

What is a more elegant way of doing this:

select date from table where id in (
  select max(id) from table);

Surely there is a better way...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱,才寂寞 2024-08-25 12:38:46

您可以使用 ROWNUM 伪列。在找到第一行之前,必须使用子查询来对结果进行排序:

SELECT date 
FROM (SELECT * FROM table ORDER BY id DESC)
WHERE ROWNUM = 1;

您可以使用 子查询在 Oracle 9i 及更高版本中,按以下方式分解

WITH ranked_table AS (
    SELECT ROWNUM AS rn, date
    FROM table
    ORDER BY id DESC
)
SELECT date FROM ranked_table WHERE rn = 1;

您可以使用自联接,并查找不存在具有更大 id 的行的位置:

SELECT date
FROM table t1
LEFT OUTER JOIN table t2
  ON t1.id < t2.id
WHERE t2.id IS NULL;

哪种解决方案最好取决于表中的索引以及数据量和数据量。您的数据的分布。您应该测试每个解决方案,以确定哪种解决方案最有效、最快、最灵活地满足您的需求等。

You can use the ROWNUM pseudocolumn. The subquery is necessary to order the result before finding the first row:

SELECT date 
FROM (SELECT * FROM table ORDER BY id DESC)
WHERE ROWNUM = 1;

You can use subquery factoring in Oracle 9i and later in the following way:

WITH ranked_table AS (
    SELECT ROWNUM AS rn, date
    FROM table
    ORDER BY id DESC
)
SELECT date FROM ranked_table WHERE rn = 1;

You can use a self-join, and find where no row exists with a greater id:

SELECT date
FROM table t1
LEFT OUTER JOIN table t2
  ON t1.id < t2.id
WHERE t2.id IS NULL;

Which solution is best depends on the indexes in your table, and the volume and distribution of your data. You should test each solution to determine what works best, is fastest, is most flexible for your needs, etc.

戈亓 2024-08-25 12:38:46
select date from (select date from table order by id desc) 
where rownum < 2

假设你的 id 是唯一的。

编辑:使用子查询+ rownum

select date from (select date from table order by id desc) 
where rownum < 2

assuming your ids are unique.

EDIT: using subquery + rownum

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文