1

我正在寻找一个查询来删除数据库中用户的所有记录。有一个表用户:

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 ???

谢谢

4

2 回答 2

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;
于 2013-08-17T13:44:01.610 回答
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>
于 2013-08-17T12:36:21.290 回答