简体   繁体   中英

Delete all related records from multiple tables

I have a table for a survey, and wants to delete all records that are related to one certain survery.

My tables:

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

Let's say I wanna delete all records that are related to surveyID 1.

I tried:

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

Two ways:

  • Set up foreign key constraints with ON DELETE CASCADE .
  • Use a multiple-table DELETE statement.

Try this:

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          

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

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