删除所有与依赖表没有任何链接的行

lf3rwulv  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(286)

我有两张table。一个是 students 另一个是
studentPerformance students 表包含 id , name 以及
email_id studentPerformance 表包含 id , student_id , marks 我的问题是,我怎样才能把所有的学生从 students 表中没有任何记录 studentPerformance table?
我搜索过谷歌,但没有找到合适的地方。
谢谢。

ncecgwcz

ncecgwcz1#

你可以用 not exists , not in ,或 left join / where :

delete s from students s
   where not exists (select 1 from studentperformance sp where sp.student_id = s.id);
ylamdve6

ylamdve62#

左连接:

DELETE s 
 FROM Students AS s 
 LEFT JOIN StudentPerformance AS sp
  ON sp.student_id = s.id 
 WHERE sp.student_id IS NULL; -- where not match was found (no sp-row)

或不存在:

DELETE s 
 FROM Students AS s 
 WHERE NOT EXISTS (SELECT 1 FROM StudentPerformance AS sp WHERE sp.student_id = s.id);
l3zydbqr

l3zydbqr3#

--运行此脚本并观察结果
创建表#students(id int,name varchar(20),email#id varchar(30))
在#students(id,name,email#id)值中插入(1,'jan','jan@gmail.com'),(2,'彼得','peter@gmail.com'),(7,'皮埃尔','pierre@gmail.com'),(12,'彼得','peter@gmail.com' )
创建表#studentperformance(id int,student id int,marks int)
在#studentperformance(id,student id,marks)值中插入(1,2,6),(1,7,8)
从id不在的学生中删除学生(从学生表现中选择学生id)
--学生1和12没有表演,所以他们被删除了
--学生2和7不会被删除
从#学生中选择*
下桌#学生
下桌#学生表现

相关问题