我有这样的表:
Table A:
`id | name`
Table B:
`id | A_id | ....`
A_id is a foreign key to Table A, the Engine is InnoDB
这是失败的代码:
String[] cleanupQueries = new String[] { "DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name = 'test')",
"DELETE FROM A WHERE name = 'test'" };
Connection connection;
try {
connection = DriverManager.getConnection(getConnectionString());
connection.setAutoCommit(false);
} catch (SQLException e) {
throw new RuntimeException("Error establishing a database connection!");
}
try {
for(String cleanupQuery : cleanupQueries) {
PreparedStatement statement = connection.prepareStatement(cleanupQuery);
statement.executeUpdate(); //FAILS WHEN EXECUTING THE SECOND QUERY
}
} catch(SQLException e) {
throw new RuntimeException("Error while executing the queries in the transactional context!");
}
try {
connection.commit();
} catch (SQLException e) {
rollback(connection);
throw new RuntimeException("Error while comitting!");
}
我得到的例外是:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails ('DATABASE/TABLE', CONSTRAINT 'FK_B_A' FOREIGN KEY ('FK_A') REFERENCES 'A' ('ID') ON DEL)
数据库不允许我删除A,但仍有B,但第一个查询删除了所有B的。我想删除所有B和他们完全引用的A.
我不想更改表以进行级联删除。我该怎么做以使代码工作?
答案 0 :(得分:0)
错误原因是
外键引用了表A id,因此如果要删除F_Key,首先应删除该外键的子引用值,然后才能删除父键。
如果我错了,请纠正我。
答案 1 :(得分:0)
删除外键约束时,只需添加级联为true。删除原始父条目时,将自动删除子表条目。
答案 2 :(得分:0)
尝试:
"DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name IN 'test')"
答案 3 :(得分:0)
由于在同一事务中删除了子行,因此删除的行仍然可见,因此无法删除父行。 这可能是因为连接上的事务隔离设置。我会尝试不同的级别,看看哪一个允许它。