Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 是否基于一个表从4个表中删除行?_Mysql_Sql - Fatal编程技术网

Mysql 是否基于一个表从4个表中删除行?

Mysql 是否基于一个表从4个表中删除行?,mysql,sql,Mysql,Sql,我正在寻找一个查询来删除数据库中某个用户的所有记录。有一个表用户: user_id | name 一桌柱 post_id | user_id | post_html 一张桌子贴着标签 id | post_id | tag_id 单表标签 id | user_id | tag 我希望从这4个表中删除与用户链接的所有记录。。。 像 谢谢我同意zerkms-您可以使用级联外键。但它也可以编写为SQL查询,但如果您有外键,则必须按正确的顺序执行,例如: delete from posts_tag

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

user_id | name
一桌柱

post_id | user_id | post_html
一张桌子贴着标签

id | post_id | tag_id
单表标签

id | user_id | tag
我希望从这4个表中删除与用户链接的所有记录。。。 像


谢谢

我同意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>

我同意虫族-你可以使用级联外键。但它也可以编写为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>

如果您愿意,可以在一个语句中完成:

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;

如果您愿意,可以在一个语句中完成:

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;

只需执行4个删除查询。就这样。可以执行多个查询,而不是一个查询。或者在cascade中使用外键,我必须在一段时间内查询表POST以检查所有POST,然后每次进行2次查询以从POST中删除\u标记和标记。。。这不是很干净,不是吗?只需执行4个删除查询。就这样。可以执行多个查询,而不是一个查询。或者在cascade中使用外键,我必须在一段时间内查询表POST以检查所有POST,然后每次进行2次查询以从POST中删除\u标记和标记。。。这不是很干净,不是吗?@RomanPekar。它是MySQL特有的。我不知道是否有其他数据库以这种方式扩展删除。就个人而言,我通常会使用四个查询,因为我使用多个不同的数据库。不起作用:当我放置现有用户id时,修改了0个对齐…:-@用户2670167。此查询假设用户在所有表中都有相应的记录。那可能不是真的。那可能不是真的。-这使得查询毫无意义…:-@罗曼佩卡。它是MySQL特有的。我不知道是否有其他数据库以这种方式扩展删除。就个人而言,我通常会使用四个查询,因为我使用多个不同的数据库。不起作用:当我放置现有用户id时,修改了0个对齐…:-@用户2670167。此查询假设用户在所有表中都有相应的记录。那可能不是真的。那可能不是真的。-这使得查询毫无意义…:-