根据一列或两列选择所有重复的行?

时间:2014-02-15 07:27:47

标签: mysql duplicates

我有一个名为contacts的表格,其中包含字段

+-----+------------+-----------+
| id  | first_name | last_name |
+-----+------------+-----------+

我想基于first_name和(/或)last_name显示所有重复项,例如:

+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
|  1 | mukta      | chourishi |
|  2 | mukta      | chourishi |
|  3 | mukta      | john      |
|  4 | carl       | thomas    |
+----+------------+-----------+

如果仅在first_name上搜索,则应返回:

+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+

但如果first_namelast_name上的搜索都应返回:

+----+
| id |
+----+
|  1 |
|  2 |
+----+

2 个答案:

答案 0 :(得分:6)

实现结果的一种方法是使用嵌套查询和having子句:在内部查询中选择那些计数多于一的那些,并在外部查询中选择id:

检查以下示例,了解单列选择标准:

创建表格:

CREATE TABLE `person` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `first` varchar(120) NOT NULL,
    `last` varchar(120) NOT NULL
);

插入元组:

INSERT INTO `person` ( `first`, `last`) VALUES
("mukta", "chourishi"),
("mukta", "chourishi"),
("mukta", "john"),
("carl", "thomas" );

您需要的结果:

mysql> SELECT  `id` 
    -> FROM `person` 
    -> WHERE `first`=(SELECT `first` FROM `person` HAVING COUNT(`first`) > 1);
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+
3 rows in set (0.00 sec)

<强> [ANSWER]

但好像您的选择标准是基于多个列,那么您可以使用JOIN。

为了解释它,我正在编写一个选择查询,该查询创建一个将在JOIN中用作第二个操作数表的中间表。

查询是选择所有拳头名称和列与其他一些行重复:
例如,选择firstlast名称重复的行

mysql> SELECT `first`, `last`,  count(*)  as rows 
    -> FROM `person` 
    -> GROUP BY `first`, `last` 
    -> HAVING count(rows) > 1;
+-------+-----------+------+
| first | last      | rows |
+-------+-----------+------+
| mukta | chourishi |    2 |
+-------+-----------+------+
1 row in set (0.00 sec)

因此,您只有一对firstlast个名称重复(或与其他一些行重复)。

现在,问题是:如何选择此行的id?使用加入!如下:

mysql> SELECT  p1.`id`
    -> FROM `person` as p1
    -> INNER JOIN (
    ->     SELECT `first`, `last`,  count(*)  as rows
    ->     FROM `person` 
    ->     GROUP BY `first`, `last` 
    ->     HAVING count(rows) > 1) as p
    -> WHERE p.`first` = p1.`first` and p.`last` = p1.`last`;  
+----+
| id |
+----+
|  1 |
|  2 |
+----+
2 rows in set (0.06 sec)

您可以根据需要选择尽可能多的列,例如单列如果要使用连接,则删除姓氏。

答案 1 :(得分:-1)

并编写sql函数,它接受firstname和lastname两个参数,如果lastname = null,则在函数内部找到firstname的重复项,如果firstname为null,则查找lastname的重复项,依此类推< / p>

条件中的状态网是

-- to show the duplicates for firstname
select id from table where first_name='name' 

-- to show duplicates for firstname and last name
select id from table where first_name='name' and last_name='lname' 

-- to show duplicates for firstname or last name
select id from table where first_name='name' or last_name='lname' 
相关问题