0

I am trying to delete record from 3 tables in 1 sql query in php. First, I tried it with delete records from two tables. This is the query for that:

DELETE pa, pr FROM pollanswers pa INNER JOIN pollresults pr ON
pa.PollQuestionId=pr.PollQuestionId WHERE pa.PollQuestionId = '123';

The problem is, what if there is no PollQuestionId in one of these table.. And other thing after that how to integrate it with third table?

Thanks.

1
  • What about accepting correct answer?? Commented Aug 19, 2015 at 12:34

3 Answers 3

3

You should not delete from multiple tables in one query.

You can define foreign key constraints on the tables with ON DELETE CASCADE option.

Then deleting the record from parent table removes the records from child tables.

Check this link : http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

Sign up to request clarification or add additional context in comments.

5 Comments

It'll work in either case.. pollquestion id might not be in any one of the table..
can you tell me how to join 3 tables?
Why you want to do it in just one query? Why not do 3 queries?
By doing it in 3 different queries is not the elegant way to do things. It will take more process time. :)
It will not take "more" process time... query will delete the same count of records. But you can define foreign key constraints, that will help you...
0

I have figured it out guys.. Thanks for your effort...

here is the query to join 3 tables:

DELETE po, pa, pr FROM posts po
LEFT JOIN pollanswers pa ON pa.PollQuestionId=po.PostId
LEFT JOIN pollresults pr ON pr.PollQuestionId=po.PostId
WHERE po.PostId = '123';

3 Comments

This will not work in all cases. And also, only thing you changed is INNER JOIN to LEFT JOIN, as I told you first, but also its not correct. F.e.: if there is PollQuestionId only in the second table pollanswers, it will not work...
I got your point.. But in my case it's not possible to have pollanswers without postid.
Can you provide ON DELETE CASCADE with 1 example here. Thanks.
-1

To join a third table, you could add another inner join:

DELETE pa, pr FROM pollanswers pa
INNER JOIN pollresults pr ON pa.POllQuestionID=pr.PollQuestionId
INNER JOIN pollwhatevers pw ON pw.whatevercolumn=pa.PollquestionID
WHERE pa.PollQuestionId = '123';

But if you want to join it to a table that is the result of joining PollResults and PollAnswers, you may want to consider using a temporary table. See this link for more information,I'm not sure I can explain it as well as this does:

http://devzone.advantagedatabase.com/dz/webhelp/Advantage7.1/adssql/using_temporary_tables_in_sql_statements.htm

Comments

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.