如何在mysql中删除唯一记录?

时间:2019-03-14 02:14:15

标签: mysql sql mysqli

我有一个这样的表

rowID | StudentName | rollNo | Class
      |             |        |
1     | ABC         |10      |  5   
2     | ABC         |10      |  5
3     | xyz         |11      |  5
4     | asd         |12      |  5

如何删除班级为unique的所有5记录

这样我剩下的桌子是

rowID | StudentName | rollNo | Class
      |             |        |
1     | ABC         |10      |  5  

2 个答案:

答案 0 :(得分:1)

我认为这可以满足您的要求

select min(id), StudentName, rollNo, Class
from t
where class = 5
group by StudentName, rollNo, Class
having count(*) > 1;

如果您确实想删除记录,那么您需要使用delete

delete t
    from t left join
         (select studentname, rollno, class, min(id) as min_id, count(*) as cnt
          from t
          group by studentname, rollno, class
         ) tt
         on t.id = tt.minid and tt.cnt > 1
    where tt.minid is null;

答案 1 :(得分:0)

尝试这个

DELETE t1 FROM table t1
        INNER JOIN
    table t2 
WHERE
    t1.rowID < t2.rowID AND t1.StudentName = t2.StudentName and t1.rollNo=t2.rollNo

这会删除所有重复的行,而剩下的行rowID最高