我有两张table。一个是 students 另一个是 studentPerformance students 表包含 id , name 以及 email_id studentPerformance 表包含 id , student_id , marks 我的问题是,我怎样才能把所有的学生从 students 表中没有任何记录 studentPerformance table? 我搜索过谷歌,但没有找到合适的地方。 谢谢。
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);
3条答案
按热度按时间ncecgwcz1#
你可以用
not exists
,not in
,或left join
/where
:ylamdve62#
左连接:
或不存在:
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不会被删除
从#学生中选择*
下桌#学生
下桌#学生表现