SQL检查不同字段中的重复值

时间:2015-08-19 13:16:25

标签: mysql sql

您好,我有一个数据库和一个名为datalist的表,它有一些虚拟数据。以下是phpmyadmin中表格的屏幕截图。

enter image description here

我想要做的是在每个字段中输出重复项。如您所见,有2个1111和2个2222数据,但它们都来自不同的字段。我怎样才能输出如下内容:

Duplicates:
1111
2222

我很抱歉我的问题,但我只知道在同一字段上检查重复数据。希望有人能帮助我,谢谢!

1 个答案:

答案 0 :(得分:4)

SELECT
  f,
  COUNT(*)   overall_occurrences,
  COUNT(CASE WHEN field = 1 THEN f END)   AS f1_occurrences,
  COUNT(CASE WHEN field = 2 THEN f END)   AS f2_occurrences,
  COUNT(CASE WHEN field = 3 THEN f END)   AS f3_occurrences,
  COUNT(CASE WHEN field = 4 THEN f END)   AS f4_occurrences
FROM
(

    SELECT 1 AS field, f1 AS f, datalist.* FROM datalist
    UNION ALL
    SELECT 2 AS field, f2 AS f, datalist.* FROM datalist
    UNION ALL
    SELECT 3 AS field, f3 AS f, datalist.* FROM datalist
    UNION ALL
    SELECT 4 AS field, f4 AS f, datalist.* FROM datalist
)
   pivotted
WHERE
   somefield = 0
GROUP BY
   f
HAVING
   COUNT(*) > 1

编辑 :已更新,以便另外显示重复项的位置。

<强> 修改 ;稍微少重复逻辑的替代方案......

(这里可能没有必要,但是在更复杂的场景中可以使用的方法示例。)

SELECT
  f,
  COUNT(*)   overall_occurrences,
  COUNT(CASE WHEN field = 1 THEN f END)   AS f1_occurrences,
  COUNT(CASE WHEN field = 2 THEN f END)   AS f2_occurrences,
  COUNT(CASE WHEN field = 3 THEN f END)   AS f3_occurrences,
  COUNT(CASE WHEN field = 4 THEN f END)   AS f4_occurrences
FROM
(

    SELECT
        pivotter.field,
        CASE pivotter.field
            WHEN 1 THEN datalist.f1
            WHEN 2 THEN datalist.f2
            WHEN 3 THEN datalist.f3
            WHEN 4 THEN datalist.f4
        END   AS f,
        datalist.*
    FROM
        datalist
    CROSS JOIN
    (
        SELECT 1 AS field
        UNION ALL
        SELECT 2 AS field
        UNION ALL
        SELECT 3 AS field
        UNION ALL
        SELECT 4 AS field
    )
        AS pivotter
)
   pivotted
WHERE
   somefield = 0
GROUP BY
   f
HAVING
   COUNT(*) > 1