0

我有这样的表:

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。

我不想将表更改为具有级联删除。我该怎么做才能使代码正常工作?

4

4 回答 4

0

只需在删除外键约束时添加级联为真。删除原始父条目时,子表条目会自动删除。

于 2012-10-29T13:04:55.970 回答
0

尝试:

"DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name IN 'test')"
于 2012-10-29T13:12:46.477 回答
0

错误的原因是

外键引用了表 A id,因此如果您想删除 F_Key ,首先您应该删除该外键的子引用值,然后才可以删除父。

如果错了请纠正我..

于 2012-10-29T12:51:45.457 回答
0

由于子行在同一个事务中被删除,因此删除的行仍然可见,因此无法删除父行。这可能是因为连接上的事务隔离设置。我会尝试不同的级别,看看哪一个允许它。

于 2018-04-11T23:32:50.303 回答