Mysql 是否基于一列或两列选择所有重复行?
我有一个名为Mysql 是否基于一列或两列选择所有重复行?,mysql,duplicates,Mysql,Duplicates,我有一个名为contacts的表,其中包含字段 +-----+------------+-----------+ | id | first_name | last_name | +-----+------------+-----------+ 我想根据名字和(/或)姓氏显示所有重复项,例如: +----+------------+-----------+ | id | first_name | last_name | +----+------------+-----------+ | 1
contacts
的表,其中包含字段
+-----+------------+-----------+
| id | first_name | last_name |
+-----+------------+-----------+
我想根据名字和(/或)姓氏显示所有重复项,例如:
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1 | mukta | chourishi |
| 2 | mukta | chourishi |
| 3 | mukta | john |
| 4 | carl | thomas |
+----+------------+-----------+
如果仅在first\u name
上搜索,则应返回:
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
+----+
但是如果同时搜索名字
和姓氏
,则应返回:
+----+
| id |
+----+
| 1 |
| 2 |
+----+
然后编写sql函数,它接受两个参数firstname和lastname,在函数内部编写条件,如果lastname=null,则为firstname查找重复项,如果firstname为null,则为lastname查找重复项,依此类推
条件中的状态是
-- 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'
实现结果的一种方法是使用嵌套查询和having子句:在内部查询中选择count大于1的查询,在外部查询中选择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)
[回答]
但是,如果选择条件基于多个列,则可以使用JOIN
为了解释这一点,我正在编写一个选择查询,该查询创建一个中间表,该中间表将在联接中用作第二个操作数表
查询是选择所有第一个名称,并将这些重复项与其他一些行列在一起:
例如,选择重复first
和last
名称的行
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)
因此,只有一对first
和last
名称重复(或与其他行重复)
现在的问题是:如何选择此行的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)
您可以根据需要选择任意多个列,例如,如果要使用“联接”则选择单列,然后删除姓氏。我建议您重新阅读问题。OP需要所有重复的行。我弄糊涂了。@GrijeshChauhan我想你需要再读一遍:)因为他想显示重复行的ID,只看他的预期结果它显示重复行的ID显示你检查了表中的重复项吗?我没有传递任何参数。只需要根据特定条件显示重复项。哦谢谢你,格里耶什。你让我今天过得很愉快……这个问题做得很好。