汇总通过约束忽略组

时间:2011-12-27 23:56:08

标签: mysql group-by having rollup

+----+-------+-------+
| id | style | color |
+----+-------+-------+
|  1 |     1 | red   |
|  2 |     1 | blue  |
|  3 |     2 | red   |
|  4 |     2 | blue  |
|  5 |     2 | green |
|  6 |     3 | blue  |
+----+-------+-------+

查询:

SELECT style, COUNT(*) as count from t GROUP BY style WITH ROLLUP HAVING count > 1;

产生

+-------+-------+
| style | count |
+-------+-------+
|     1 |     2 |
|     2 |     3 |
|  NULL |     6 |
+-------+-------+

我需要做什么才能让WITH ROLLUP仅将那些符合HAVING要求的计数加起来?也就是说,我希望在汇总行中看到“5”表示计数。

1 个答案:

答案 0 :(得分:4)

这完全令人费解和讨厌,但我明白了

SELECT style,COUNT(1) as count
FROM t
WHERE NOT EXISTS
(
    SELECT t1.style as count
    FROM
    (
        SELECT style from t GROUP BY style HAVING count(*) = 1
    ) t1 WHERE t.style = t1.style
)
GROUP BY style
WITH ROLLUP;

以下是问题的示例数据:

drop database if exists rollup_test;
create database rollup_test;
use rollup_test
create table t (id int not null auto_increment,
style int,color varchar(10),primary key (id));
insert into t (style,color) values
(1,'red'),(1,'blue'),(2,'red'),
(2,'blue'),(2,'green'),(3,'blue');
select * from t;

这里加载了:

mysql> drop database if exists rollup_test;
Query OK, 1 row affected (0.07 sec)

mysql> create database rollup_test;
Query OK, 1 row affected (0.00 sec)

mysql> use rollup_test
Database changed
mysql> create table t (id int not null auto_increment,
    -> style int,color varchar(10),primary key (id));
Query OK, 0 rows affected (0.10 sec)

mysql> insert into t (style,color) values
    -> (1,'red'),(1,'blue'),(2,'red'),
    -> (2,'blue'),(2,'green'),(3,'blue');
Query OK, 6 rows affected (0.05 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> select * from t;
+----+-------+-------+
| id | style | color |
+----+-------+-------+
|  1 |     1 | red   |
|  2 |     1 | blue  |
|  3 |     2 | red   |
|  4 |     2 | blue  |
|  5 |     2 | green |
|  6 |     3 | blue  |
+----+-------+-------+
6 rows in set (0.00 sec)

mysql>

以下是查询的结果:

mysql> SELECT style,COUNT(1) as count
    -> FROM t
    -> WHERE NOT EXISTS
    -> (
    ->     SELECT t1.style as count
    ->     FROM
    ->     (
    ->         SELECT style from t GROUP BY style HAVING count(*) = 1
    ->     ) t1 WHERE t.style = t1.style
    -> )
    -> GROUP BY style
    -> WITH ROLLUP;
+-------+-------+
| style | count |
+-------+-------+
|     1 |     2 |
|     2 |     3 |
|  NULL |     5 |
+-------+-------+
3 rows in set (0.00 sec)

mysql>

问题是在WITH ROLLUP之前评估HAVING。我以最后WITH ROLLUP完成的方式安排了查询。

任务完成!!!