2014-02-15 50 views
3

我有一个带有字段名为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 | 
+----+ 
+0

阅读更新后的答案。 –

回答

5

一体,实现你的结果的方法是使用嵌套查询和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

哦,谢谢Grijesh。你刚刚过完我的一天...查询工作完美。 – user3286692

+0

@ user3286692没有得到你吗?你想在最后的评论中说什么? –

-1

和你写的SQL函数,它有两个参数名字和姓氏和功能里面你写你的条件,如果姓氏= NULL找到名字重复了,如果名字为空,找到重复的姓氏,等等等等

的条件内statemnets是

-- 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' 
+0

我建议你再读一遍问题。 OP要求所有行都是重复的。我迷惑。 –

+0

@GrijeshChauhan我想你需要再读一遍:)因为他想显示重复行的ID只看他的预期结果 –

+0

它显示重复的ID –