使用php从多个表mysql中删除

时间:2017-02-17 22:54:55

标签: php mysql sql

我已经尝试过在互联网上发现的关于从同一查询中的多个表中删除的所有内容,但它最终会从第一个表中删除(帖子)..

那么如何使用php和pdo以正确的方式执行此操作?

我尝试过的例子=

$dsn = "DELETE FROM Posts, Comments USING Posts, Comments WHERE Posts.ID = Comments.PostID  AND Comments.PostID=:my var";

$dsn = "DELETE FROM Posts LEFT JOIN Comments ON `Comments.PostID` = `Posts.ID` WHERE `Posts.ID`=:tit";

$dsn = "DELETE Posts , Comments  FROM Posts  INNER JOIN Comments  WHERE Posts.ID = Comments.PostID and Posts.ID =:myvar";

表格如下:

 TABLE: Posts

    ID(PK AI) 
    Title(VARCHAR)
    Post(VARCHAR)
    Author(VARCHAR)
    Date(DATETIME)



TABLE: Comments

ID(PK AI so all comments get unique id's)
Name(VARCHAR)
Comment(VARCHAR)
Date(DATETIME
PostID(INT)

1 个答案:

答案 0 :(得分:1)

你有不同的方法来解决这个问题:
1- 使用内部联接删除

$dsn = "DELETE Posts.*, Comments.*  FROM Posts  INNER JOIN Comments  WHERE Posts.ID = Comments.PostID and Posts.ID =:myvar";

2- 删除级联,如果存在外键则删除并执行此操作:

ALTER TABLE Comments
  ADD CONSTRAINT fk_postid 
  FOREIGN KEY (PostID) 
  REFERENCES Posts(ID) 
  ON DELETE CASCADE;

3- 在表格中删除后使用触发器

  delimiter $$
    CREATE TRIGGER `after_delete_Posts`     
      AFTER DELETE ON `Posts`     
      FOR EACH ROW     
    BEGIN
      DELETE FROM Comments where PostID = OLD.id;
    END
    $$
    delimiter ;