[英]mysql - filter query result based on count of one column's value?
I am running the following mysql query: 我正在运行以下mysql查询:
SELECT visitnum, userid
FROM user_visit
WHERE date >= '2015-10-31 00:00:00' AND date <= '2015-11-01 23:59:59'
Which returns me the following results: 返回以下结果:
visitnum userid
2010 60265
2011 60264
2012 60264
2013 60268
2014 60269
2015 60269
2016 60269
As you can see, this means the user 60265 and 60268 has one visit; 如您所见,这意味着用户60265和60268有一次访问。 user 60264 has two visits and user 60269 has three visits. 用户60264有两次访问,用户60269有3次访问。
Now - how do I modify my mysql query so that it returns me only the rows associated with users that only visit ONCE? 现在-如何修改mysql查询,使其仅返回与仅访问ONCE的用户相关联的行? In other words, I expect my query to return me the following result: 换句话说,我希望查询返回以下结果:
visitnum userid
2010 60265
2013 60268
And how do I modify the query to return me only the rows that associated with users that only visit TWICE? 以及如何修改查询以仅返回与仅访问TWICE的用户相关联的行? like this: 像这样:
visitnum userid
2011 60264
2012 60264
You can use this trick: 您可以使用以下技巧:
SELECT max(visitnum) as visitnum, userid
FROM user_visit
WHERE date >= '2015-10-31 00:00:00' AND date <= '2015-11-01 23:59:59'
GROUP BY usserid
HAVING COUNT(*) = 1;
The trick here is that MAX(visitnum)
is the one-and-only visit number, when there is only one row in the group. 这里的技巧是,当组中只有一行时, MAX(visitnum)
是唯一的访问号。
An alternative way that doesn't use GROUP BY
is: 不使用GROUP BY
的另一种方法是:
select uv.*
from user_visits uv
where not exists (select 1
from user_visits uv2
where uv2.userid = uv.userid and uv.visitnum <> uv2.visitnum
);
This should have better performance, if you have in an index on user_visits(userid, visitnum)
. 如果您在user_visits(userid, visitnum)
上有一个索引,这应该有更好的性能。
SELECT visitnum, userid
FROM user_visit
WHERE userid IN (
SELECT userid
FROM user_visit
WHERE date >= '2015-10-31 00:00:00' AND date <= '2015-11-01 23:59:59'
GROUP BY userid
HAVING COUNT(*) = 2
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.