Tell me more ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Suppose,I've a table called UNIVERSITY containing universities name:

universityID    universityNAME  isACTIVE
     7            GNDU             1
     6            PU               1
     5            PTU              1
     8            LPU              1

Now these universities ID's has been(obviously) used in many tables within the database(name e.g.Education),Suppose 10 tables.

Q.Now what happen if i delete one university?

A.The universityID field in other tables becomes NULL.

But I don't want these,rather when I delete 1 university from UNIVERSITY TABLE,all its occurrences with Rows in all 10 table should get deleted.

What will be the shortest and easiest MySQL Query for this operation.

NOTE:I'm using PHP language.

share|improve this question
2  
If you have 10 tables with Foreign Keys that reference University, change the 10 FKs to have the attribute ON DELETE CASCADE. – ypercube Nov 7 '12 at 7:15
And use InnoDB. – dezso Nov 7 '12 at 10:28

1 Answer

You can do this something like that

$query = "SELECT universityID FROM UNIVERSITY WHERE universityNAME='PTU'";
$result = mysql_query($query);
$id = mysql_fetch_assoc($result);

//Create an array of tables from which you want to delete university reference
$tables = array('xyz','abc','test');

foreach($tables as $table) {
     $query = "DELETE FROM $table WHERE universityID=$id->universityID";
     mysql_query($query);
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.