查找具有重复/类似列值MySQL的行

我想从下表中选择fname列中具有相似值的所有行作为它们的顺序中的第一行.从这张表中我想要检索带有ids 2,5和7的行(因为“anna”出现在“anna”之后,而“michaela”和“michaal”出现在“michael”之后).

+----+------------+----------+
| id | fname      | lname    |
+----+------------+----------+
|  1 | anna       | milski   |
|  2 |  anna      | nguyen   |
|  3 | michael    | michaels |
|  4 | james      | bond     |
|  5 | michaela   | king     |
|  6 | bruce      | smart    |
|  7 | michaal    | hardy    |
+----+------------+----------+

到目前为止我所拥有的是:

select *, count(fname) cnt 
from users group by soundex(fname) 
having count(soundex(fname)) > 1;

但是因为我正在对它进行分组,结果是

+----+----------+----------+-----+
| id | fname    | lname    | cnt |
+----+----------+----------+-----+
|  1 | anna     | milski   |   2 |
|  3 | michael  | michaels |   3 |
+----+----------+----------+-----+

我想要检索的是:

+----+----------+----------+-----+
| id | fname    | lname    | cnt |
+----+----------+----------+-----+
|  2 |  anna    | nyugen   |   2 |
|  5 | michaela | king     |   3 |
|  7 | michaal  | hardy    |   3 |
+----+----------+----------+-----+

我应该对查询做些什么改变?我尝试删除“分组依据”,但它改变了结果(我可能是错的,没有广泛测试).

解决方法:

我已经重新阅读了您的初步问题,我想出了以下解决方案:

SELECT *
FROM   users
WHERE  id IN
       (SELECT id
       FROM    users t4
               INNER JOIN
                       (SELECT  soundex(fname) AS snd,
                                COUNT(*)       AS cnt
                       FROM     users          AS t5
                       GROUP BY snd
                       HAVING   cnt > 1
                       )
                       AS t6
               ON      soundex(t4.fname)=snd
       )
AND    id NOT IN
       (SELECT  MIN(t2.id) AS wanted
       FROM     users t2
                INNER JOIN
                         (SELECT  soundex(fname) AS snd,
                                  COUNT(*)       AS cnt
                         FROM     users          AS t1
                         GROUP BY snd
                         HAVING   cnt > 1
                         )
                         AS t3
                ON       soundex(t2.fname)=snd
       GROUP BY snd
       );

这有点过于复杂,但它的工作原理与您提出的要求完全相同:)

上一篇:PHP在DB中插入重复项


下一篇:mysql – 在插入之前插入检查重复的语句