与LAST_INSERT_ID()
类似,MySQL删除行后是否有一个很好的机制来获取最后删除的ID?
答案 0 :(得分:9)
通过“ID”,我假设你的意思是“自动增量”?
由于您可以随时删除任意行(或行集):否,无法告知您最近删除的行(或行)。
你可以,但是,创建一个“触发器”来为您保存这些信息:
答案 1 :(得分:4)
除了创建触发器之外,您还需要在每次删除时使用它
declare @table1 table(id int identity,name varchar(50))
insert into @table1 (name) values('abc')
insert into @table1 (name) values('xyz')
insert into @table1 (name) values('pqr')
insert into @table1 (name) values('wqe')
delete from @table1 output deleted.name,deleted.id where id=3
答案 2 :(得分:1)
这取决于你如何删除。但是如果你有一个整数id列,你可以使用以下hack:
DELETE FROM users
WHERE login = 'newtover' AND user_id = LAST_INSERT_ID(user_id);
SELECT LAST_INSERT_ID();
但是你应该确保MySQL将前一个条件短路并且不优化以首先运行user_id = LAST_INSERT_ID(user_id)
。也就是说,您可以将查询调整为:
DELETE FROM users
WHERE login = 'newtover' AND IFNULL(user_id, 0) = LAST_INSERT_ID(user_id);
P.S。我不问你为什么需要这个。最有可能的是,你不应该想要它=)
答案 3 :(得分:0)
如果您正在从JDBC调用MySQL数据库,那么您可以执行videojs.options.flash.swf = 'path/relative/to/page.swf'
并在阅读结果时调用SELECT
并获取ID。
ResultSet.deleteRow()
示例表
import java.sql.*;
public class Delete {
public static void main(String... args) throws SQLException {
try(Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=john&password=denver");
PreparedStatement statement = conn.prepareStatement("select id from some_table where event=?")
) {
statement.setString(1, "test");
try(ResultSet result = statement.executeQuery()) {
System.out.println("deleting id " + result.getLong("id"));
result.deleteRow();
}
conn.commit();
}
}
}
答案 4 :(得分:0)
已经提到了使用last_insert_id的hack,但是那个答案 错过了它可以聚合的事实!
最后一个插入ID具有固定大小,但对于小键,可以使用它。
mysql> insert into t1 () values (),(),(),(),(),(),();
Query OK, 7 row affected (0.00 sec)
mysql> select * from t1;
+---+
| n |
+---+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
+---+
7 rows in set (0.00 sec)
select last_insert_id(0); -- clear accumulator
+-------------------+
| last_insert_id(0) |
+-------------------+
| 0 |
+-------------------+
1 row in set (0.00 sec)
-- keys will be separated by zeroes
mysql> delete from t1
where last_insert_id(last_insert_id()
* pow(10, 2 + floor(log(n)/log(10))) + n)
limit 6;
Query OK, 6 rows affected (0.00 sec)
mysql> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 10203040506 |
+------------------+
1 row in set (0.00 sec)
-- rows deleted
mysql> select * from t1 limit 1;
+---+
| n |
+---+
| 7 |
+---+
1 row in set (0.00 sec)