删除多个表中的所有相关记录

时间:2012-05-06 21:42:35

标签: mysql

我有一个调查表,并希望删除与某个调查相关的所有记录。

我的桌子:

_______________     _______________     ___________  ________________
|_tblSurvey___|     |_tblAnswers___|    |_tblAlt__|  |_tblQuestions_|
| surveyID    |     | answerAltID  |    | altID   |  | questID      |
| surveyName  |     | userID       |    | altText |  | questText    |
|_____________|     |______________|    |_questID_|  |_surveyID_____|

假设我想要删除与surveyID 1相关的所有记录。

我试过了:

DELETE 
 * 
FROM tblSurvey, tblQuestions, tblAlt, tblAnswers
WHERE tblSurvey.surveyID = 1 
AND tblsurvey.surveyID = tblQuestions.surveyID
AND tblQuestions.questID = tblAlt.questID
AND tblAlt.altID = tblAnswers.answerAltID

2 个答案:

答案 0 :(得分:8)

两种方式:

  • 使用ON DELETE CASCADE设置外键约束。
  • 使用多表DELETE声明。

试试这个:

DELETE tblSurvey, tblQuestion, tblAlt, tblAnswers 
FROM tblSurvey
JOIN tblQuestion ON tblsurvey.surveyID = tblQuestion.surveyID
JOIN tblAlt ON tblQuestions.questID = tblAlt.questID
JOIN tblAnswers ON tblAlt.altID = tblAnswers.answerAltID 
WHERE tblSurvey.surveyID = 1          

答案 1 :(得分:2)

如果您的表具有外键引用,则可以使用ON DELETE CASCADE