使用内部联接删除不起作用

时间:2013-08-06 05:10:23

标签: mysql sql

我正在从多个表中删除与游戏ID相对应的游戏。

以下是我正在使用的查询

$sql = DELETE `tb_games`, `tb_game_over`, `tb_game_round_record` FROM `tb_games`";
$sql .= " INNER JOIN `tb_game_over` ON `tb_games`.`game_id` = `tb_game_over`.`game_id`";
$sql .= " INNER JOIN `tb_game_round_record` ON `tb_games`.`game_id` = `tb_game_round_record`.`game_id`";
$sql .= " WHERE `tb_games`.`game_id` = ?";

如果game_id在所有三个表中,则此查询有效但如果游戏ID仅在tb_games表中则不起作用。我该如何解决这个问题?或者我是否需要编写三个不同的查询来从所有三个表中删除?

2 个答案:

答案 0 :(得分:0)

您可以通过将tb_game_over和tb_game_round_record外键中的game_id列指向tb_games.game_id并包含'on delete cascade'子句来消除在DML中执行此操作的需要。然后你的删除语句将如下所示:

delete from tb_games where game_id=?

答案 1 :(得分:0)

只需你可以做

DELETE FROM tb_games WHERE game_id IN (
SELECT game_id FROM tb_game_over
UNION ALL
SELECT game_id FROM tb_game_round_record
);