简体   繁体   English

使用内部联接从多个表中删除

[英]delete from multiple table with inner join

I am trying to delete record from 3 tables in 1 sql query in php. 我试图从PHP中的1个SQL查询中的3个表中删除记录。 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? 问题是,如果其中一个表中没有PollQuestionId,那么如何将其与第三个表集成?

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. 您可以使用ON DELETE CASCADE选项在表上定义外键约束。

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 请访问此链接: 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: 这是连接3个表的查询:

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. 但是,如果要将其加入到加入PollResults和PollAnswers的结果表中,您可能需要考虑使用临时表。 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 http://devzone.advantagedatabase.com/dz/webhelp/Advantage7.1/adssql/using_temporary_tables_in_sql_statements.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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