如何获取Oracle表的最后一行

gr8qqesn  于 2023-05-28  发布在  Oracle
关注(0)|答案(8)|浏览(335)

我想获取最后一行,这是我插入到Oracle 11g Express数据库中的表中的。我该怎么做?

46scxncf

46scxncf1#

表中没有“最后”行,因为Oracle表没有顺序的概念。
然而,假设你想找到最后插入的主键 *,并且 * 这个主键是一个递增的数字,你可以这样做:

select *
  from ( select a.*, max(pk) over () as max_pk
           from my_table a
                )
 where pk = max_pk

如果你有每一行的创建日期,如果列名为created,这将变成:

select *
  from ( select a.*, max(created) over () as max_created
           from my_table a
                )
 where created = max_created

或者,您可以使用聚合查询,例如:

select *
  from my_table
 where pk = ( select max(pk) from my_table )

这里有一个小SQLFiddle来演示。

hmmo2u0o

hmmo2u0o2#

SELECT * FROM (
    SELECT * FROM table_name ORDER BY sortable_column DESC
) WHERE ROWNUM = 1;
bkkx9g8r

bkkx9g8r3#

select * from table_name ORDER BY primary_id DESC FETCH FIRST 1 ROWS ONLY;

这是最简单的一个,不做子查询

lnvxswe2

lnvxswe24#

根据复合密钥K(k1,...,kn)上的严格全序的最后一行:

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
                OR  (i.k1 = o.k1 AND i.k2 > o.k2)
                ...
                OR  (i.k1 = o.k1 AND i.k2 = o.k2 AND i.k3 = o.k3 AND ... AND i.kn > o.kn)
        )
;

假设K是简单的特殊情况(即非复合),上述内容缩短为:

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
        )
;

请注意,对于只返回一行的查询,键必须按顺序排列,不带连接。如果允许绑定,则此查询将返回与最大键绑定的所有行。

44u64gxh

44u64gxh5#

你可以这样做:

SELECT * FROM (SELECT your_table.your_field, versions_starttime
               FROM your_table
               VERSIONS BETWEEN TIMESTAMP MINVALUE AND MAXVALUE)
WHERE ROWNUM = 1;

或者:

SELECT your_field,ora_rowscn,scn_to_timestamp(ora_rowscn) from your_table WHERE ROWNUM = 1;
5rgfhyps

5rgfhyps6#

SELECT * FROM 
  MY_TABLE
WHERE 
  <your filters>
ORDER BY PRIMARY_KEY DESC FETCH FIRST ROW ONLY
ovfsdjhp

ovfsdjhp7#

SELECT /*+ index_desc(t pk_index)*/
    pk
  FROM TBL t
 WHERE ROWNUM = 1;
pgky5nke

pgky5nke8#

$sql = "INSERT INTO table_name( field1, field2 )  VALUES ('foo','bar') 
        RETURNING ID INTO :mylastid";
$stmt = oci_parse($db, $sql);
oci_bind_by_name($stmt, "mylastid", $last_id, 8, SQLT_INT);
oci_execute($stmt);

echo "last inserted id is:".$last_id;

**提示:**您必须在下面的{your_id_col_name}中使用您的id列名...

"RETURNING {your_id_col_name} INTO :mylastid"

相关问题