如果我想选择从不同IP访问网站的用户,SQL SELECT查询应该如何?
这是表的内容:
id | ip | userid | timecreated
1 | 192.0.0.1 | 1 | 111111111
2 | 192.0.0.1 | 3 | 111111111
3 | 192.0.0.2 | 1 | 111111111
4 | 192.0.0.3 | 2 | 111111111
5 | 192.0.0.2 | 2 | 111111111
执行必要的SQL SELECT查询应该选择如下:
id | ip | userid | timecreated
1 | 192.0.0.1 | 1 | 111111111
3 | 192.0.0.2 | 1 | 111111111
4 | 192.0.0.3 | 2 | 111111111
5 | 192.0.0.2 | 2 | 111111111
任何人都可以帮我吗?
提前谢谢!
答案 0 :(得分:1)
如果您希望拥有多个IP的用户:
SELECT DISTINCT userid FROM myTable GROUP BY ip HAVING COUNT(*) > 1;
为了获得他们的完整记录(就像你在问题中所说的那样):
SELECT * FROM myTable WHERE userid IN (
SELECT DISTINCT userid FROM myTable GROUP BY ip HAVING COUNT(*) > 1
);
答案 1 :(得分:0)
获取userid
只是一个带有having
子句的简单聚合:
select userid
from t
group by userid
having min(ip) <> max(ip);
如果您想要详细的行,可以使用join
或in
:
select t.*
from t join
(select userid
from t
group by userid
having min(ip) <> max(ip)
) tt
using (userid);