这是创建表的脚本:
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;
该职位表没有外键client_id
,唯一的project_id
.我想删除已通过的项目中的帖子client_id
.
现在这不起作用,因为没有删除任何帖子.
您只需指定要从posts
表中删除条目:
DELETE posts FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id
编辑:有关更多信息,您可以看到这个替代答案
由于您要选择多个表,因此要删除的表不再明确.你需要选择:
DELETE posts FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id
在这种情况下,table_name1
并且table_name2
是相同的表,所以这将工作:
DELETE projects FROM posts INNER JOIN [...]
如果您想要,您甚至可以从两个表中删除:
DELETE posts, projects FROM posts INNER JOIN [...]
请注意,order by
并且limit
不适用于多表删除.
另请注意,如果声明表的别名,则在引用表时必须使用别名:
DELETE p FROM posts as p INNER JOIN [...]
来自Carpetsmoker等的贡献.
或者同样的事情,略有不同(IMO友好)的语法:
DELETE FROM posts USING posts, projects WHERE projects.project_id = posts.project_id AND projects.client_id = :client_id;
顺便说一句,使用连接的mysql几乎总是比子查询更快...
您也可以像这样使用ALIAS它只是在我的数据库中使用它!t是需要删除的表格!
DELETE t FROM posts t INNER JOIN projects p ON t.project_id = p.project_id AND t.client_id = p.client_id
我更习惯于子查询解决方案,但我还没有在MySQL中尝试过:
DELETE FROM posts WHERE project_id IN ( SELECT project_id FROM projects WHERE client_id = :client_id );
MySQL使用JOIN删除记录
通常在SELECT语句中使用INNER JOIN从表中选择具有其他表中相应记录的记录.我们还可以使用带有DELETE语句的INNER JOIN子句来删除表中的记录以及其他表中的相应记录,例如,要删除满足特定条件的T1和T2表中的记录,请使用以下语句:
DELETE T1, T2 FROM T1 INNER JOIN T2 ON T1.key = T2.key WHERE condition
请注意,您将表名T1和T2放在DELETE和FROM之间.如果省略T1表,则DELETE语句仅删除T2表中的记录,如果省略T2表,则仅删除T1表中的记录.
连接条件T1.key = T2.key指定T2表中需要删除的相应记录.
WHERE子句中的条件指定需要删除T1和T2中的哪些记录.
单表删除:
要从posts
表中删除条目:
DELETE ps FROM clients C INNER JOIN projects pj ON C.client_id = pj.client_id INNER JOIN posts ps ON pj.project_id = ps.project_id WHERE C.client_id = :client_id;
要从projects
表中删除条目:
DELETE pj FROM clients C INNER JOIN projects pj ON C.client_id = pj.client_id INNER JOIN posts ps ON pj.project_id = ps.project_id WHERE C.client_id = :client_id;
要从clients
表中删除条目:
DELETE C FROM clients C INNER JOIN projects pj ON C.client_id = pj.client_id INNER JOIN posts ps ON pj.project_id = ps.project_id WHERE C.client_id = :client_id;
多个表删除:
要从联接结果中删除多个表中的条目,您需要在DELETE
逗号分隔列表后指定表名:
假设你想从所有三个表(删除条目posts
,projects
,clients
)为特定的客户端:
DELETE C,pj,ps FROM clients C INNER JOIN projects pj ON C.client_id = pj.client_id INNER JOIN posts ps ON pj.project_id = ps.project_id WHERE C.client_id = :client_id
尝试如下:
DELETE posts.*,projects.* FROM posts INNER JOIN projects ON projects.project_id = posts.project_id WHERE projects.client_id = :client_id;