我有2个msql表(记录和播放器)whitch包含以下字段:
records = Id PlayerId Score Date Checkpoints
players = Id Login Game NickName Nation UpdatedAt Wins TimePlayed TeamName
我从播放器db中删除了几个,我将从记录表中删除此值。
db中的Id值相同。
我使用了这个命令:
DELETE FROM `players` WHERE `players`.`Id` = 27;
但删除后,Id` = 27仍然存在于记录表中。
所以现在玩家表中没有id 27但是我会从记录中删除它。 我还有120个参赛作品:(
答案 0 :(得分:1)
如果您希望在从records
删除时自动从players
表中删除相关行,则需要将PlayerId
声明为ON DELETE CASCADE
的外键选项。
ALTER TABLE records ADD CONSTRAINT fk_playerid FOREIGN KEY (PlayerId) REFERENCES players (id) ON DELETE CASCADE;
这只有在您使用InnoDB时才有效;在MyISAM中忽略外键。
如果您不能使用外键,则可以在删除时加入表格:
DELETE p, r FROM players AS p
LEFT JOIN records AS r ON p.id = r.PlayerId
WHERE p.id = 27;
这需要使用LEFT JOIN
;如果您使用INNER JOIN
,则不会删除没有相关记录的玩家。
答案 1 :(得分:0)
使用内部联接
尝试此操作DELETE records, players FROM records INNER JOIN players
WHERE records.Id= players.Id and records.Id = '27'
这应该删除表格
如果您在一个表中不存在记录:
DELETE records, players FROM records INNER JOIN players
WHERE records.Id != players.Id
答案 2 :(得分:0)
DELETE FROM records WHERE NOT PlayerId IN (SELECT Id FROM players)
这将删除所有不属于玩家的记录。