Home > Database > Mysql Tutorial > How to Delete Records from a Child Table Using a JOIN in MySQL?

How to Delete Records from a Child Table Using a JOIN in MySQL?

DDD
Release: 2025-01-20 17:13:11
Original
532 people have browsed it

How to Delete Records from a Child Table Using a JOIN in MySQL?

Use JOIN to delete subtable records in MySQL

In relational databases such as MySQL, deleting records may involve multiple tables and complex relationships. One scenario is when you need to delete records from a child table based on a condition involving the parent table.

Scene:

Consider the following database structure:

  • clients table, client_id as primary key
  • projects table, project_id as primary key, client_id as foreign key
  • posts table, post_id as primary key, project_id as foreign key

Target:

Suppose you wish to delete all posts associated with a given client by deleting the client itself. However, the posts table does not reference client_id directly. It only references project_id.

Initial attempt (invalid):

<code class="language-sql">DELETE 
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;</code>
Copy after login

Solution:

In order to correct the problem and successfully delete the post, you need to specify the table name (posts) in the DELETE statement:

<code class="language-sql">DELETE posts
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;</code>
Copy after login

This modified query explicitly targets the posts table for deletion based on the join conditions.

The above is the detailed content of How to Delete Records from a Child Table Using a JOIN in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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