Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all related records from multiple tables

Tags:

mysql

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
like image 322
janlindso Avatar asked May 06 '12 21:05

janlindso


People also ask

How delete all records from multiple tables in SQL?

The syntax also supports deleting rows from multiple tables at once. To delete rows from both tables where there are matching id values, name them both after the DELETE keyword: DELETE t1, t2 FROM t1 INNER JOIN t2 ON t1.id = t2.id; What if you want to delete nonmatching rows?

Can you delete from multiple tables at once SQL Server?

We know how to delete data from a single table, however, if you are confronted with a situation where you want to delete data from one table and also any related data from other tables, you can employ the multi-table delete in SQL.

How can I delete two rows from two different tables with a single query?

MySQL DELETE JOIN with INNER JOIN MySQL also allows you to use the INNER JOIN clause in the DELETE statement to delete rows from a table and the matching rows in another table. Notice that you put table names T1 and T2 between the DELETE and FROM keywords.


1 Answers

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          
like image 154
Mark Byers Avatar answered Sep 20 '22 16:09

Mark Byers