java 即使外键不存在也删除两个表的联接

06odsfpq  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(122)

下面的方法删除了另一个表中有相同外键的房间和消息,但是如果房间没有消息就不删除。我用的是mysql8和java11。

public void deleteRoom() {
        // TODO Auto-generated method stub
        try {
            PreparedStatement preparedStatement = this.databaseMySQL.getConnection().
                    prepareStatement("DELETE OS_ROOMS, OS_ROOM_MESSAGES FROM OS_ROOMS INNER JOIN OS_ROOM_MESSAGES WHERE OS_ROOMS.ROS_ID = OS_ROOM_MESSAGES.ROM_ROS_ID AND OS_ROOMS.ROS_ID = ?");
            preparedStatement.setInt(1, RoomChatSession.id);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

我搜索了delete case,比如这个

"DELETE OS_ROOMS, OS_ROOM_MESSAGES FROM OS_ROOMS INNER JOIN OS_ROOM_MESSAGES WHERE (OS_ROOMS.ROS_ID = OS_ROOM_MESSAGES.ROM_ROS_ID AND OS_ROOMS.ROS_ID = ?) OR (OS_ROOMS_ID = ?)"

'我想删除房间,即使它没有消息,它是可能的使用只对sql命令?

1zmg4dgp

1zmg4dgp1#

请使用MySQL中连接两个表的不同方法。您的sql语句执行交集,而您只需要将消息Map到房间。因此,您需要使用LEFT JOIN而不是INNER JOIN,您的查询将变为:

DELETE OS_ROOMS, OS_ROOM_MESSAGES FROM OS_ROOMS LEFT JOIN OS_ROOM_MESSAGES ON OS_ROOMS.ROS_ID = OS_ROOM_MESSAGES.ROM_ROS_ID WHERE OS_ROOMS.ROS_ID = ?

相关问题