我有一个包含member_information的表及其引用代理。我想运行一个查询,该查询返回表中的所有信息(select *),其中代理出现的次数超过3次。
我的初步查询是:
SELECT agent FROM activity GROUP BY agent ASC HAVING COUNT(agent) > 3;
这将返回所需的代理ID,但不返回“活动”中的其他数据。
我修改为:
SELECT * FROM activity GROUP BY agent ASC HAVING COUNT(agent) > 3
这只返回所需的每个代理编号的结果之一,而不是所有具有匹配代理编号的行。
我错过了什么?
假设表结构如下:
id | agent | name | address
--------------------------------------------------------
1 | 1 | (name) | (an address)
2 | 1 | (name) | (an address)
3 | 2 | (name) | (an address)
4 | 3 | (name) | (an address)
5 | 3 | (name) | (an address)
6 | 3 | (name) | (an address)
7 | 1 | (name) | (an address)
8 | 2 | (name) | (an address)
9 | 4 | (name) | (an address)
查询结果应该返回:
id | agent | name | address
--------------------------------------------------------
1 | 1 | (name) | (an address)
2 | 1 | (name) | (an address)
4 | 3 | (name) | (an address)
5 | 3 | (name) | (an address)
6 | 3 | (name) | (an address)
7 | 1 | (name) | (an address)
答案 0 :(得分:4)
使用:
SELECT x.*
FROM ACTIVITY x
JOIN (SELECT t.agent
FROM ACTIVITY t
GROUP BY t.agent
HAVING COUNT(t.agent) > 3) y ON y.agent = x.agent
答案 1 :(得分:1)
分组时,组中的所有行都会压缩为一个。根据您要执行的操作,您需要使用适当的组函数(SUM,GROUP_CONCAT等),或者您可以执行我认为您尝试使用子查询执行的操作:
SELECT * FROM activity WHERE agent IN (select agent from activity group by agent asc having count(agent) > 3);