gpt4 book ai didi

mysql - rollup 通过约束忽略组

转载 作者:行者123 更新时间:2023-11-29 04:53:50 27 4
gpt4 key购买 nike

+----+-------+-------+
| 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”的计数。

最佳答案

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

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 ROLLUPHAVING 之前计算。我以 WITH ROLLUP 最后完成的方式安排了查询。

任务完成!!!

关于mysql - rollup 通过约束忽略组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8650506/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com