返回重复记录

时间:2011-05-04 15:08:13

标签: mysql ruby-on-rails duplicates

我只是想从表中返回重复记录。在我的情况下,如果多个记录在col1,col2,col3和col4中具有相同的值,则记录重复。

2 个答案:

答案 0 :(得分:5)

SELECT col1, col2, col3, col4
     , COUNT(*) AS cnt
FROM yourTable
GROUP BY col1, col2, col3, col4
HAVING COUNT(*) > 1

如果您想要显示其他列,可以JOIN上面的表格:

SELECT t.*
     , dup.cnt
FROM yourTable t
    JOIN
      ( SELECT col1, col2, col3, col4
             , COUNT(*) AS cnt
        FROM yourTable
        GROUP BY col1, col2, col3, col4
        HAVING COUNT(*) > 1
      ) AS dup
      ON  t.col1 = dup.col1
      AND t.col2 = dup.col2
      AND t.col3 = dup.col3
      AND t.col4 = dup.col4

答案 1 :(得分:1)

SELECT  m.*
FROM    (
        SELECT  col1, col2, col3, col4, COUNT(*)
        FROM    mytable
        GROUP BY
                col1, col2, col3, col4
        HAVING  COUNT(*) > 1
        ) md
JOIN    mytable m
ON      m.col1 = md.col1
        AND m.col2 = md.col2
        AND m.col3 = md.col3
        AND m.col4 = md.col4