我正在寻找一个查询来删除数据库中用户的所有记录。有一个表用户:
user_id | name
一个表格帖子
post_id | user_id | post_html
一个表posts_tags
id | post_id | tag_id
一个表标签
id | user_id | tag
我希望从这4个表中删除链接到用户的所有记录... 喜欢
delete from tags t inner join posts_tags bt on t.id = bt.tag_id where ???
谢谢
答案 0 :(得分:3)
如果您愿意,可以在一个声明中完成:
delete u, p, pt, t
from users u join
posts p
on u.id = p.user_id join
posts_tags pt
on p.id = pt.post_id join
tags t
on t.id = pt.tag_id
where u.id = @YOURUSERID;
答案 1 :(得分:1)
我同意zerkms - 您可以使用级联外键。但它也可以写成SQL查询,但如果你有外键,你必须按正确的顺序执行,如:
delete from posts_tags
where
tag_id in (select id from tags where user_id = <your user id>) or
post_id in (select post_id from posts where user_id = <your user id>)
delete from tags
where user_id = <your user id>
delete from posts
where user_id = <your user id>
delete from users
where user_id = <your user id>