我有一个名为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_name
和last_name
上搜索,则应返回:
+----+
| id |
+----+
| 1 |
| 2 |
+----+
实现结果的一种方法是使用嵌套查询和have子句:在内部查询中选择计数大于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。
为了解释这一点,我正在编写一个选择查询,该查询创建一个中间表,该表将在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
?使用Join!如下所示:
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)
您可以根据需要选择任意多列,例如,如果您想使用联接,则可以选择单列,然后删除姓氏。
然后编写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'