【发布时间】:2011-03-30 21:34:19
【问题描述】:
谁能帮我写一个 sql select 来执行任务。 所以问题是我们有一张桌子并且有一些重复,所以我需要找到名称、街道和房屋相同的地方,并以某种方式对它们进行分组。
我几乎有this 的情况,但不同的是我想将它们分组以查找与什么重复的内容。
提前致谢。
【问题讨论】:
谁能帮我写一个 sql select 来执行任务。 所以问题是我们有一张桌子并且有一些重复,所以我需要找到名称、街道和房屋相同的地方,并以某种方式对它们进行分组。
我几乎有this 的情况,但不同的是我想将它们分组以查找与什么重复的内容。
提前致谢。
【问题讨论】:
这是假设您有一个 id 字段,该字段将与每个重复行的 GROUP_CONCAT() 函数分组:
SELECT t1.name, t1.street, t1.house, GROUP_CONCAT(DISTINCT t1.id) dupes
FROM your_table t1
JOIN your_table t2 ON (t2.name = t1.name AND
t2.street = t1.street AND
t2.house = t1.house)
GROUP BY t1.name, t1.street, t1.house
HAVING COUNT(*) > 1;
测试用例:
CREATE TABLE your_table (
id int,
name varchar(10),
street varchar(10),
house varchar(10)
);
INSERT INTO your_table VALUES (1, 'a', 'b', 'c');
INSERT INTO your_table VALUES (2, 'a', '1', 'c');
INSERT INTO your_table VALUES (3, 'a', '2', '3');
INSERT INTO your_table VALUES (4, 'a', 'b', 'c');
INSERT INTO your_table VALUES (5, 'a', 'b', 'c');
INSERT INTO your_table VALUES (6, 'c', 'd', 'e');
INSERT INTO your_table VALUES (7, 'c', 'd', 'e');
结果:
+------+--------+-------+-------+
| name | street | house | dupes |
+------+--------+-------+-------+
| a | b | c | 1,5,4 |
| c | d | e | 6,7 |
+------+--------+-------+-------+
2 rows in set (0.03 sec)
【讨论】:
GROUP_CONCAT()。想象在上面的示例中,我们有另一个名为 value 的列,第 1 行的 value 为 100,第 2 行的 value 为 200,依此类推。现在,由于我们将最终结果集分组以仅显示行有重复的,value 列应该是什么? 100、400 还是 500? (因为所有这 3 条记录都分组在一行中)...但是我们可以使用 GROUP_CONCAT(value) 将此列作为逗号分隔的字段,就像 dupes 列一样。
要获得重复项,只需在表上使用自联接:
select t1.id, t2.id, t1.name, t1.street, t1.house
from table t1
inner join table t2 on t1.name=t2.name and t1.street=t2.street and t1.house=t2.house
where t1.id < t2.id
t1.id
【讨论】: