如何获取oracle表中最后插入的记录

问题描述 投票:0回答:2

我有一个名为 orderdetails 的表。其中我有名为 ID 的列,它是主键。我想获取该表中最近添加的记录。我曾经使用 ID 过滤掉 desc 中插入的最后一个值,因为那是主键。但这里主键没有排序。它创建随机值,所以我无法选择最后一个值

select *
from orderdetail
where Id = (SELECT LAST_INSERT_ID());
sql oracle primary-key
2个回答
0
投票

长话短说,你不能这样做。

不适用于您当前拥有的桌子。

必须有一列明确指出最后插入的是哪一行。它是时间戳、序列号、标识列(在后台也使用序列)还是您可以想象的任何其他内容,必须有这样一个值。

你能做什么?忘记该表中当前存在的行,您无法从中挽救任何内容。

更改表并添加新列;如果您将使用序列号填充它,则为

number

数据类型;如果您将插入时间戳,则为

date
数据类型。请注意,如果您同时插入很多行,则可以同时插入两行或更多行,因此序列可能是更好的选择。
假设您将使用一个序列。创建它(

create sequence new_seq

就可以)。然后在每个

insert
语句中手动使用它,例如
insert into that_table (pk_column, name, created_on, new_sequence_column)
  values (f_random, 'Little', sysdate, new_seq.nextval);

或创建一个
before insert

触发器

create or replace trg_bi_tab
  before insert on that_table
  for each row
begin
  :new.new_sequence_column := new_seq.nextval;
end;
/

并将 
insert

修改为

insert into that_table (pk_column, name, created_on)
  values (f_random, 'Little');

new_sequence_column

将自动填充)。

然后你会例如

with temp as (select t.*, row_number() over (order by new_sequence_column desc) rn from that_Table ) select * from temp where rn = 1;

select * From that_Table where new_sequence_column = (select max(new_sequence_column) from that_table);

或您认为合适的任何其他查询。

附注看看这个
AskTom

讨论;您将看到演示,其中显示可能的 smart 查询(使用 ROWNUMROWID 或其他任何查询)中的

none
根本不起作用。
    


0
投票

SELECT * FROM orderdetail WHERE ROWNUM = (SELECT MAX(ROWNUM) FROM orderdetail);

© www.soinside.com 2019 - 2024. All rights reserved.