DELETE FROM不适用于多个表 - 对mysql无能为力

时间:2012-05-19 08:00:36

标签: php mysql

基本上,我有三张桌子

具有字段ID的工作场所(我想删除其中一个关联数据),以及标识参与者列表的participantlist_id。

参与者列表 - 只是list_id和名称

participantlist_links - 使用list_id和participant_id

我正在尝试使用的查询是:

DELETE FROM workplaces,
participantlist,
participantlist_links 
WHERE workplaces.id =  '8' AND 
      workplaces.participantlist_id = participantlist_links.list_id AND  
      workplaces.participantlist_id = participantlist.list_id

但我明白了:

MySQL说:

1064 - 您的SQL语法出错;查看与您的MySQL服务器版本对应的手册,以便在'WHERE workplaces.id ='8'和'workplaces.participantlist_id =参与者'第3行附近使用正确的语法

任何想法?

解决方案:

    DELETE t1, t2, t3
    FROM workplaces AS t1
    LEFT JOIN participantlist AS t2 ON t1.participantlist_id = t2.list_id
    LEFT JOIN participantlist_links AS t3 ON t2.list_id = t3.list_id
    WHERE t1.id = '8'

4 个答案:

答案 0 :(得分:2)

您是否考虑过将ON DELETE CASCADE放在外键上? 这样,当您从工作空间中删除行时,其他行也将自动删除。

有关更多信息,请参阅此链接: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

否则你必须使用单独的DELETE FROM查询来删除它们。

在执行这些删除时使用事务是明智的。因此,如果出现任何问题,您可以回滚您的更改:

BEGIN TRANSACTION;
DELETE FROM ......;
DELETE FROM ......;
COMMIT;

答案 1 :(得分:1)

尝试

DELETE workplaces, participantlist, participantlist_links FROM workplaces,
participantlist,
participantlist_links 
WHERE workplaces.id =  '8' AND 
      workplaces.participantlist_id = participantlist_links.list_id AND  
      workplaces.participantlist_id = participantlist.list_id

答案 2 :(得分:1)

正如the manual中所提到的,DELETE的多表格形式与您正在使用的语法具有不同的语法。你想要:

DELETE workplaces, participantlist, participant_links
FROM   workplaces
  JOIN participantlist
    ON workplaces.participantlist_id = participantlist.list_id
  JOIN participantlist_links
    ON workplaces.participantlist_id = participantlist_links.list_id
WHERE  workplaces.id = '8'

答案 3 :(得分:1)

您可以使用JOIN从多个表中删除,如下所示:

DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;

http://dev.mysql.com/doc/refman/5.5/en/delete.html