0

I have literally tried everything i've found on the internet about deleting from multiple tables in same query, but it just ends up deleting from the first table(Posts)..

So how does one do this the correct way with php and pdo?

examples of what i've tried=

$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";

The tables looks as following:

 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)
9
  • 3
    If you define Coments.PostID as FK with ON DELETE CASCADE, you will just need to delete from Posts. Commented Feb 17, 2017 at 23:17
  • @PaulSpiegel that sounds intressting, just need to find out how to do that then :) Commented Feb 17, 2017 at 23:31
  • Look at the first example here: dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html Commented Feb 17, 2017 at 23:33
  • post an MCVE. post your tables Commented Feb 17, 2017 at 23:35
  • @e4c5 sorry, im not sure what you mean Commented Feb 17, 2017 at 23:46

1 Answer 1

1

You have different ways to solve this:
1- delete with inner join

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

2- delete cascade, drop if exist foreing key and execute this:

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

3- using trigger after delete in the table Posts

  delimiter $$
    CREATE TRIGGER `after_delete_Posts`     
      AFTER DELETE ON `Posts`     
      FOR EACH ROW     
    BEGIN
      DELETE FROM Comments where PostID = OLD.id;
    END
    $$
    delimiter ; 
Sign up to request clarification or add additional context in comments.

3 Comments

I tried with the cascade, i dropped the FK and AI on ID in comments then ran your query and got this: #1452 - Cannot add or update a child row: a foreign key constraint fails (pelle.#sql-c32d_67e16, CONSTRAINT fk_postid FOREIGN KEY (PostID) REFERENCES Posts (ID) ON DELETE CASCADE) i have tried the delete query before, it doesnt work im afraid
The definition of the data type of both postID and ID are the same?
before alter table add this:SET FOREIGN_KEY_CHECKS=0; ,and after add SET FOREIGN_KEY_CHECKS=1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.