在表格中查找重复条目

时间:2011-09-18 16:50:26

标签: php mysql sql

我有一个messcuts表,其结构如下 idstudent_rollnodate

问题是有一些记录重复,即。在同一student_rollno中具有相同date的两个记录。我该如何删除它们?例如:

SELECT * 
FROM  `messcuts` 
WHERE student_rollno =  'b070226'

|id |student_rollno|date
|259|B070226|2011-08-06
|260|B070226|2011-08-07
|1485|B070226|2011-08-12
|1486|B070226|2011-08-13
|1487|B070226|2011-08-14
|1488|B070226|2011-08-15
|2372|B070226|2011-08-27
|2369|B070226|2011-08-24
|2368|B070226|2011-08-23
|2371|B070226|2011-08-26
|2374|B070226|2011-08-29
|2373|B070226|2011-08-28
|2370|B070226|2011-08-25
|2367|B070226|2011-08-22
|2375|B070226|2011-08-30
|2376|B070226|2011-08-31
|2938|b070226|2011-08-06

见2011-08-06有两条记录。

2 个答案:

答案 0 :(得分:7)

select student_rollno, date 
from messcuts 
group by student_rollno, date 
having count(*) > 1

并删除:

delete from messcuts d where d.id in (
    select max(s.id) 
    from messcuts as s 
    group by s.student_rollno, s.date 
    having count(*) > 1)

如果不在mysql中工作:

delete from messcuts 
using messcuts, messcuts as v_messcuts
where messcuts.id <> v_messcuts.id
and messcuts.student_rollno = v_messcuts.student_rollno
and messcuts.date = v_messcuts.date

答案 1 :(得分:-1)

这将显示重复项

SELECT * 
FROM messcuts
WHERE (student_rollno,date) IN
    (
    SELECT student_rollno,date
    FROM messcuts
    GROUP BY student_rollno,date
    HAVING count(*)>1
    )

并删除:

CREATE VIEW dups AS
SELECT MAX(id) as id
    FROM messcuts
    GROUP BY student_rollno,date
    HAVING count(*)>1

你需要多次运行才能摆脱所有重复

DELETE FROM t2 
WHERE id IN (SELECT  id FROM dups)

删除重复项后添加唯一约束来阻止更新问题可能是个好主意。

ALTER TABLE messcuts ADD UNIQUE std_dte (student_rollno,date)