从MySQL中的多个表删除

时间:2018-11-23 22:40:27

标签: php mysql sql-delete

我想结合以下两个查询。记录将始终存在于用户表和active_kpi表中,但它们可能不存在于收件人表中。即使记录不在收件人表中,我仍然希望查询从其他两个表中删除记录。

    $sql = "DELETE u, ak FROM users u JOIN active_kpi ak ON ak.group_id = 
    u.group_id WHERE u.group_id = ?";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([$group_id]);

    $sql = "DELETE FROM recipients WHERE group_id = ?";
    $stmt = $this->db->prepare($sql);
    $stmt->execute([$group_id]);

1 个答案:

答案 0 :(得分:1)

尝试:

DELETE u,ak,r
FROM users u INNER JOIN active_kpi ak ON ak.group_id = u.group_id 
    LEFT JOIN recipients r ON ak.group_id = r.group_id
WHERE u.group_id = ?

请注意,left join用于覆盖缺少收件人的行。