简体   繁体   English

删除具有相同值的最后一个插入记录

[英]Delete the last insert record with the same values

I have the following records inside a table: 我在表中有以下记录:

User     Product     Quantity
A        Test 1      5
A        Test 1      3
B        Test 1      4
B        Test 2      1

When I run 'DELETE FROM Sample WHERE User='A' AND Product='Test 1' , I want to delete the last inserted record: 当我运行'DELETE FROM Sample WHERE User='A' AND Product='Test 1'中删除'DELETE FROM Sample WHERE User='A' AND Product='Test 1' ,我想删除最后插入的记录:

User     Product     Quantity
    A        Test 1      5
    B        Test 1      4
    B        Test 2      1

Is this possible? 这可能吗? Please advise. 请指教。

Here's a working sql fiddle based on my comments. 这是根据我的评论工作的SQL小提琴

Note that in the fiddle example I added an id and last_edited columns. 请注意,在小提琴示例中,我添加了一个id和last_edited列。 I use GetDate() to fill the date time but add successive days( getdate() + 1..n ) to force unique date times... 我使用GetDate()填充日期时间,但添加连续的几天(getdate()+ 1..n)以强制唯一的日期时间...

The answer isn't the smoothest but demonstrates what I was talking about in the comments, and is correct. 答案不是最流畅,但可以证明我在评论中正在谈论的内容是正确的。 By the way, you didn't specify the version of SQL Server but if it's 2012 you should use the new, higher-precision date time type and also add a unique index on the column since your date times need to be unique identifiers in this scenario. 顺便说一句,您没有指定SQL Server的版本,但是如果是2012,则应该使用新的,更高精度的日期时间类型,并在列上添加唯一索引,因为您的日期时间必须是该字段中的唯一标识符。场景。 Do you use the surrogate id though! 您是否使用代理人ID!

Repeating comments here: 在此处重复评论:

What does "last" mean in your table? 表格中的“最后”是什么意思? Without a date time column you cannot deterministically calculate which record was temporally placed last in the table. 如果没有日期时间列,则无法确定性地计算出哪个记录​​在时间上位于表的最后。 There is no internal metadata, in SQL Server at least, that would give you such info... I would also suggest using a surrogate primary key since none of your values are unique. 至少在SQL Server中,没有内部元数据可以为您提供此类信息...我也建议您使用代理主键,因为您的值都不是唯一的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM