Home > Database > Mysql Tutorial > How to Correctly Delete Rows Across Multiple Tables in MySQL?

How to Correctly Delete Rows Across Multiple Tables in MySQL?

Barbara Streisand
Release: 2025-01-19 10:26:10
Original
196 people have browsed it

How to Correctly Delete Rows Across Multiple Tables in MySQL?

MySQL cross-table deletion: syntax error troubleshooting

In MySQL, deleting rows from multiple tables simultaneously requires special query syntax. When trying to execute the following delete query:

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

You may encounter the following error:

<code>Uncaught Database_Exception [ 1064 ]: You have an error in your SQL syntax; check the manual...</code>
Copy after login

This error stems from a syntax error in cross-table deletion. To solve this problem, use JOIN in DELETE 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, to delete only from the pets_activities table, you can use:

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

By using the JOIN statement in this way, you can efficiently perform cross-table delete operations in MySQL. Keep in mind that this approach also works for single-table deletes with referential integrity.

The above is the detailed content of How to Correctly Delete Rows Across Multiple Tables in MySQL?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template