Home > Database > Mysql Tutorial > How to Safely Delete Records from Multiple MySQL Tables?

How to Safely Delete Records from Multiple MySQL Tables?

Mary-Kate Olsen
Release: 2025-01-19 10:37:09
Original
299 people have browsed it

How to Safely Delete Records from Multiple MySQL Tables?

MySQL multi-table safe deletion of records

Directly using the following code to delete rows from multiple tables simultaneously may result in an error:

DELETE FROM `pets` p,
            `pets_activities` pa
      WHERE p.`order` > :order
        AND p.`pet_id` = :pet_id
        AND pa.`id` = p.`pet_id`
Copy after login

The recommended solution is to use the JOIN statement:

DELETE p, pa
      FROM pets p
      JOIN pets_activities pa ON pa.id = p.pet_id
     WHERE p.order > :order
       AND p.pet_id = :pet_id
Copy after login

Alternatively, you can just delete the records in the pets_activities table while referencing the pets table:

DELETE pa
      FROM pets_activities pa
      JOIN pets p ON pa.id = p.pet_id
 WHERE p.order > :order
   AND p.pet_id = :pet_id
Copy after login

This approach uses an alias in the FROM clause to specify the table to be dropped, and is particularly useful when dealing with complex scenarios with referential integrity.

The above is the detailed content of How to Safely Delete Records from Multiple MySQL Tables?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template