小编典典

在 MySQL 中使用 Join 删除

all

这是创建我的表的脚本:

CREATE TABLE clients (
   client_i INT(11),
   PRIMARY KEY (client_id)
);
CREATE TABLE projects (
   project_id INT(11) UNSIGNED,
   client_id INT(11) UNSIGNED,
   PRIMARY KEY (project_id)
);
CREATE TABLE posts (
   post_id INT(11) UNSIGNED,
   project_id INT(11) UNSIGNED,
   PRIMARY KEY (post_id)
);

在我的 PHP 代码中,删除客户端时,我想删除所有项目帖子:

DELETE 
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;

posts 表没有外键client_id,只有project_id. 我想删除项目中通过的帖子client_id

这现在不起作用,因为没有删除任何帖子。


阅读 128

收藏
2022-03-08

共1个答案

小编典典

您只需要指定要从posts表中删除条目:

DELETE posts
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id
2022-03-08