MySQL:在多个字段中查找重复项

时间:2011-01-08 05:02:23

标签: mysql duplicates

假设我有一个MySQL数据库,表中包含以下五个记录:

ID: 1
Field1: A
Field2: B
Field3: C

ID: 2
Field1: D
Field2: E
Field3: F

ID: 3
Field1: A
Field2: H
Field3: I

ID: 4
Field1: J
Field2: K
Field3: A

ID: 5
Field1: M
Field2: D
Field3: O

请注意以下值是重复的:

ID 1,字段1与ID 3,字段1和ID 4,字段3具有相同的值。

ID 2,字段1与ID 5,字段2具有相同的值。

是否有可以找到所有上述重复项的SELECT语句?

1 个答案:

答案 0 :(得分:6)

它是可行的但不确定它是否比在应用程序级别执行它更有效:

你的桌子:

mysql> select * from test;
+----+--------+--------+--------+
| id | field1 | field2 | field3 |
+----+--------+--------+--------+
|  1 | A      | B      | C      |
|  2 | D      | E      | F      |
|  3 | A      | H      | I      |
|  4 | J      | K      | A      |
|  5 | M      | D      | O      |
+----+--------+--------+--------+
5 rows in set (0.00 sec)

选择找到欺骗:

mysql> select count(value) as dupe_count,value from (select field1 as value from test union all select field2 from test union all select field3 from test) as tbl group by value having count(value) > 1 order by 1 desc;
+------------+-------+
| dupe_count | value |
+------------+-------+
|          3 | A     |
|          2 | D     |
+------------+-------+
2 rows in set (0.00 sec)

基本上你把三列合并成一个然后找dupes