sql 删除记录及与其关联的其他记录

假设现在有学生表students,成绩表score。属性如下

students表: ,studentId,年龄……
scores表:studentId,科目,分数……。

现在要删除其中一个学生的记录,那么同时也需要删除这个学生的成绩:
第一种删除方式是:

DELETE student.*,score.* 
FROM students student
LEFT JOIN scores as score student.studentId = score.studentId
where student.studentId = 学号

left join的好处在于如果这个学生没有分数记录,就只会删除这个学生的记录,如果有多条分数记录,那么就会删除这个学生的所有分数记录。

第二种删除方式使用inner join:

DELETE student.*,score.* 
FROM students student
INNER JOIN scores as score student.studentId = score.studentId
where student.studentId = 学号

这个删除,如果学生没成绩,学生的信息删除不了。

第三种:

DELETE student.*,score.* 
FROM students studen, scores score
where student.studentId = 学号 AND student.studentId = score.studentId

这个删除也是,如果学生没成绩,学生的信息删除不了。

猜你喜欢

转载自blog.csdn.net/whbing1471/article/details/52760148