如何对 MySQL 中具有多个 HAVING 值的多列进行 GROUP BY?
How to GROUP BY multiple columns with multiple HAVING values in MySQL?
我正在尝试创建一个 mysql 查询来查看存储搜索查询的 table。查询试图获取所有行:
>=
日期
- 仅 returning 搜索查询出现 3 次或更多次的行
- 也只有 returning 行,其中 2 个或更多用户使用了搜索查询
此查询无效,但应概述我要执行的操作:
SELECT
*
FROM
`analytics`
WHERE
`date` >= '2021-01-01'
GROUP BY
`query`
HAVING
COUNT(*) >= 3
AND
GROUP BY
`user`
HAVING
COUNT(*) >= 2
ORDER BY
id DESC;
示例数据
id
user
query
date
1
5
What is a dog
2021-01-01
2
5
What is a dog
2021-01-01
3
6
What is a dog
2021-01-01
4
7
What is a dog
2021-01-01
5
7
What is a brog
2021-01-01
例子SQL
SELECT
*
FROM
analytics
WHERE
date >= '2021-01-01'
GROUP BY
query
HAVING
COUNT(*) >= 3
AND
GROUP BY
user
HAVING
COUNT(*) >= 2
ORDER BY
id DESC;
使用上面查询中设置的值,单行应该 return 查询“What is a dog”,所有其他列并不重要。
我知道您可以用逗号分隔 GROUP BY 的列,但我似乎无法弄清楚如何为每一列设置不同的值。
您可以在同一个 HAVING
子句中设置两个条件:
SELECT `query`
FROM `analytics`
WHERE `date` >= '2021-01-01'
GROUP BY `query`
HAVING COUNT(*) >= 3 AND COUNT(DISTINCT `user`) >= 2;
我正在尝试创建一个 mysql 查询来查看存储搜索查询的 table。查询试图获取所有行:
>=
日期- 仅 returning 搜索查询出现 3 次或更多次的行
- 也只有 returning 行,其中 2 个或更多用户使用了搜索查询
此查询无效,但应概述我要执行的操作:
SELECT
*
FROM
`analytics`
WHERE
`date` >= '2021-01-01'
GROUP BY
`query`
HAVING
COUNT(*) >= 3
AND
GROUP BY
`user`
HAVING
COUNT(*) >= 2
ORDER BY
id DESC;
示例数据
id | user | query | date |
---|---|---|---|
1 | 5 | What is a dog | 2021-01-01 |
2 | 5 | What is a dog | 2021-01-01 |
3 | 6 | What is a dog | 2021-01-01 |
4 | 7 | What is a dog | 2021-01-01 |
5 | 7 | What is a brog | 2021-01-01 |
例子SQL
SELECT
*
FROM
analytics
WHERE
date >= '2021-01-01'
GROUP BY
query
HAVING
COUNT(*) >= 3
AND
GROUP BY
user
HAVING
COUNT(*) >= 2
ORDER BY
id DESC;
使用上面查询中设置的值,单行应该 return 查询“What is a dog”,所有其他列并不重要。
我知道您可以用逗号分隔 GROUP BY 的列,但我似乎无法弄清楚如何为每一列设置不同的值。
您可以在同一个 HAVING
子句中设置两个条件:
SELECT `query`
FROM `analytics`
WHERE `date` >= '2021-01-01'
GROUP BY `query`
HAVING COUNT(*) >= 3 AND COUNT(DISTINCT `user`) >= 2;