级联删除多对多表

时间:2018-08-13 09:51:51

标签: mysql cascading-deletes

假设一组邮件列表,其中个人可能是多个列表的成员。我已经建立了一个联接表:

members -> members2lists <- lists

如果用户只想从一个列表中删除一个成员,则似乎只需要删除members2lists表中的相应行。但是,如果它们仅是一个列表的成员,我如何指定级联,以免将它们留为孤儿?换句话说,当且仅当他们只是我要从中删除他们的列表的成员时,才如何删除该成员?

我在InnoDB表中使用PHP和mySQL。

1 个答案:

答案 0 :(得分:0)

感谢David的回复。我已经通过这种方式解决了这个问题(我希望前两个功能可以自我解释):

$memberID = getIDFromMembers($pdo, $email);
$currListID = getIDFromList($pdo, $listname);

// remove record from join table
$sql = 'DELETE FROM `members2lists` WHERE `member_fk` = :member AND `list_fk` = :list';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':member', $memberID);
$stmt->bindParam(':list', $currListID);
$stmt->execute();

// check if another record exists in the join table for the same member
$sql = 'SELECT `member_fk` FROM `members2lists` WHERE `member_fk` = :member';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':member', $memberID);
$stmt->execute();
$row = $stmt->fetch();

if($row === false) 
{
  // there isn't, the member is an orphan, so delete
  $sql = 'DELETE FROM `members` WHERE `member_email` = :email';
  $stmt = $pdo->prepare($sql);
  $stmt->bindParam(':email', $email);
  $stmt->execute();
}

我很高兴成员们对改进此代码的方式发表评论!