简体   繁体   中英

delete from multiple table with inner join

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.

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

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';

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM