我有下表学生,允许重复的ID如下所示:
现在在此表中,我需要删除所有其他重复记录,并留下任何一个id的唯一记录。
例如,如果执行delete语句,则应删除7条记录,留下2条记录,其中id为“1”,另一条记录为id为“2”。
如下图所示: -
[最终预期输出] [2]
如何编写单个SQL查询以获得上述结果。
下面是我正在尝试的示例sql查询,这会导致编译时错误 在sql编辑器中作为“意外的学生标识符”。
DELETE FROM student as a
WHERE a.sno not in(select b.sno from test.student as b group by b.id);
请帮我弄清楚我的错误。
提前感谢。
答案 0 :(得分:0)
您可以使用UNIQUE KEY:SNO删除它。它用于唯一标识删除操作的记录。
delete a.*
from student a
where a.sno not in (
select sno from (
select min(sno) as sno
from student
group by id) tab
);
答案 1 :(得分:0)
试试这个:
set sql_safe_updates = 0;
DELETE FROM student
WHERE sno NOT IN (
SELECT b.sno FROM (SELECT MIN(a.sno) AS sno
FROM student a GROUP BY a.id) b);
set sql_safe_updates = 1;
答案 2 :(得分:0)
delete from student where sno
not in( select st.* from (SELECT sno FROM student group by id) st);
您的查询部分正确...但是,当您按ID进行分组时,您必须再次将这些ID带到此处,然后我就会将所有ID都放在' st'。 39;并且查询将变得像
delete from student where sno
not in(1,6)