无法从多个表中删除

时间:2014-08-02 17:16:23

标签: mysql sql

我正在尝试删除通过管理员帐户创建的网站中某个人的所有记录。查询如下:

DELETE FROM users u, user_address ua, pending_order po, product_catalogue pc 
WHERE u.user_id = ua.user_id 
AND ua.user_id = po.user_id 
AND po.user_id = pc.user_id 
AND u.user_id = '$user_id'

$user_id是从表单中的$_POST['user_id']获得的。

每当我运行它时,我都会收到此错误

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'u,user_address ua,pending_order po,product_catalogue pc WHERE   u.user_id = ua。'在第1行

这里有什么问题?

5 个答案:

答案 0 :(得分:0)

您必须为每个表运行一个delete语句:

delete from users where user_id = '$user_id';
delete from user_addresses where user_id = '$user_id';
delete from pending_order where user_id = '$user_id';
delete from product_catalogue where user_id = '$user_id';

答案 1 :(得分:0)

你必须逐一删除表格:

DELETE FROM users  WHERE user_id = '$user_id';
DELETE FROM user_address WHERE user_id = '$user_id';
DELETE FROM  pending_order WHERE user_id = '$user_id';
DELETE FROM product_catalogue WHERE user_id = '$user_id'; 

如果您使用大型表和MySQL Replication,有时可能会更好(测试它!):

$rows =  SELECT group_concat(id) FROM product_catalogue WHERE user id = ...
//$rows  = 1,2,3,4,5,10,15,155 or similar list)
DELETE FROM table WHERE id in ( $rows )

当删除的项目列表很大并且我想最小化锁定和复制延迟时,我有时会这样做。

答案 2 :(得分:0)

正如documentation建议......:)

DELETE FROM users u, user_address ua, pending_order po, product_catalogue pc 
using u inner join ua inner join po inner join pc
WHERE u.user_id = ua.user_id 
AND ua.user_id = po.user_id 
AND po.user_id = pc.user_id 
AND u.user_id = '$user_id';

注意:从四个表中单独删除相应的行(如果需要,在一个事务中)可能不那么耗时。特别是如果不是所有这些,user_id是一个索引字段。

答案 3 :(得分:0)

您无法使用一个语句删除语句删除多个表。您需要单独执行此操作。这就像

DELETE FROM users  WHERE user_id = '$user_id';
DELETE FROM user_address WHERE user_id = '$user_id';
DELETE FROM  pending_order WHERE user_id = '$user_id';
DELETE FROM product_catalogue WHERE user_id = '$user_id'; 

答案 4 :(得分:0)

您可以按照上面的建议运行以下内容

DELETE FROM users  WHERE user_id = '$user_id';
DELETE FROM user_address WHERE user_id = '$user_id';
DELETE FROM  pending_order WHERE user_id = '$user_id';
DELETE FROM product_catalogue WHERE user_id = '$user_id';

一个。但为什么不设置外键关系,以达到理想的效果。

您必须在users表和其他表中创建user_id作为主键 user_address,pending_order,product_catalogue将它们声明为外键 并通过添加ON DELETE CASCADE来修改您的查询,这将删除与子表中传递的$ user_id相关联的所有记录。

湾您还可以设置MySQL触发器,只需谷歌查看触发器的详细信息。

℃。我有一个不同的建议。

为什么不在表中添加一个名为active_status的新列并将记录状态存储为Active Inactive,因此您只需更改记录的状态,而不是删除记录,您可以将其称为软删除,在更新级联中的表中使用相同的pk和fk概念。