当你对b字段排序(分组),相同值的c被分到不同的组,因此不能用COUNT(DISTINCT c)来计算大小。COUNT()之类的内部函数只作用于同一个分组,对于不同分组的行就无能为力了。类似,如果排序的是c字段,相同值的b也会分到不同的组,无论如何是不能达到我们的目的的。
几种正确的方法
也许最简单的方法是分别对某个字段查找重复行,然后用UNION拼在一起,像这样:
- select b as value, count(*) as cnt, 'b' as what_col
- from a_b_c group by b having count(*) > 1
- union
- select c as value, count(*) as cnt, 'c' as what_col
- from a_b_c group by c having count(*) > 1;
- +-------+-----+----------+
- | value | cnt | what_col |
- +-------+-----+----------+
- | 1 | 3 | b |
- | 2 | 3 | b |
- | 3 | 3 | b |
- | 1 | 3 | c |
- | 2 | 3 | c |
- | 3 | 3 | c |
- +-------+-----+----------+
输出what_col字段为了提示重复的是哪个字段。另一个办法是使用嵌套查询:
- select a, b, c from a_b_c
- where b in (select b from a_b_c group by b having count(*) > 1)
- or c in (select c from a_b_c group by c having count(*) > 1);
- +----+------+------+
- | a | b | c |
- +----+------+------+
- | 7 | 1 | 1 |
- | 8 | 1 | 2 |
- | 9 | 1 | 3 |
- | 10 | 2 | 1 |
- | 11 | 2 | 2 |
- | 12 | 2 | 3 |
- | 13 | 3 | 1 |
- | 14 | 3 | 2 |
- | 15 | 3 | 3 |
- +----+------+------+
这种方法的效率要比使用UNION低许多,并且显示每一重复的行,而不是重复的字段值。还有一种方法,将自己跟group的嵌套查询结果联表查询。写法比较复杂,但对于复杂的数据或者对效率有较高要求的情况,是很有必要的。
- select a, a_b_c.b, a_b_c.c
- from a_b_c
- left outer join (
- select b from a_b_c group by b having count(*) > 1
- ) as b on a_b_c.b = b.b
- left outer join (
- select c from a_b_c group by c having count(*) > 1
- ) as c on a_b_c.c = c.c
- where b.b is not null or c.c is not null
以上方法可行,我敢肯定还有其他的方法。如果UNION能用,我想会是最简单不过的了。