我希望在删除其ID时删除数据库中主题的全部内容。
if(isset($_GET['subject_id'])){
$subject_id = $_GET['subject_id'];}
$deleteexams = mysql_query("SELECT * FROM exam_exams where exam_subject_id = '$subject_id'")or die(mysql_query());
while($ids = mysql_fetch_array($deleteexams)){
$selected = $ids['exam_id'];
}
$deletequestions = mysql_query("SELECT * FROM exam_questions where question_exam_id = '$selected'")or die(mysql_query());
while($ids2 = mysql_fetch_array($deletequestions)){
$selectedids = $ids2['question_id'];
}
$deleteanswers = mysql_query("SELECT * FROM exam_answers where answer_question_set_id = '$selectedids'")or die(mysql_query());
while($ids3 = mysql_fetch_array($deleteanswers)){
$selectedidsans = $ids3['answer_id'];
}
/// I want to delete all of the answers inside the questions of the exams in the subject
mysql_query("DELETE * FROM exam_answers where answer_id = '$selectedidsans'")or die(mysql_error());
/////i want to delete all the questions
mysql_query("DELETE * FROM exam_questions where answer_id = '$selectedids'")or die(mysql_error());
////this will work because this has the subject ids
mysql_query("DELETE * FROM exam_exams where exam_subject_id = '$subject_id'")or die(mysql_error());
/////and this too
mysql_query("DELETE * FROM exam_subjects where subject_id = '$subject_id'")or die(mysql_error());
我的问题是如何删除答案和问题,因为它的字段中没有subject_id。
答案 0 :(得分:1)
删除*来的语法不正确。
您确实需要使用评论中提到的IN,因为您可以使用考试ID选择表格中的所有answer_id,字段名称可能会根据您的情况而改变,但逻辑将是
DELETE
FROM exam_answers
WHERE answer_id IN
(SELECT answer_id
FROM questions
WHERE question_id IN
(SELECT exam_id
FROM exams
WHERE subject_id=<yoursubjectid>))
不是一种有效的方法,实际上你可能最好在每个表中存储主题id,即使它是多余的
答案 1 :(得分:0)
将IN
与子查询一起使用也是我的第一个选择,但这里也是其他一些选项。
你在mysql表中使用外键吗?你可以让mysql通过参照完整性和级联来解决这个问题。 看这里:MySQL foreign key constraints, cascade delete
如果您只查看PHP解决方案,则应首先从使用外键的表中删除记录。 例如。首先删除考试科目,问题和答案,然后删除考试本身。
另一个选择是根本不删除记录(如果你需要某种考试历史记录)。您可以将这些记录标记为已删除或未激活,并在以后从数据库中选择数据时对其进行过滤。
像这样:SELECT * FROM exam_exams where active = 1;
您能为我们提供您的mysql创建表脚本或ERA图吗?