列出具有相同IP的用户

时间:2016-01-27 04:32:31

标签: mysql sql

我有这个查询,

SELECT * FROM users
WHERE user_ip IN (SELECT user_ip FROM users GROUP BY user_ip having count(*) > 1)
ORDER BY user_ip

这可以列出与另一个用户至少有1个重复IP的所有用户。

我需要按重复的IP总数订购所有用户。

离。这个用户表

id, username, ip
1, user1, 1.1.1.1
2, user2, 2.2.2.2
3, user3, 1.1.1.1
4, user4, 4.4.4.4
5, user5, 2.2.2.2
6, user6, 2.2.2.2

应该打印,

ip, username, total
2.2.2.2, user2, 3
2.2.2.2, user5, 3
2.2.2.2, user6, 3
1.1.1.1, user1, 2
1.1.1.1, user3, 2
4.4.4.4, user4, 1

3 个答案:

答案 0 :(得分:3)

这是一种使用INNER JOIN

的方法
SELECT u1.ip, u1.username, u2.total
FROM users u1
INNER JOIN
(
    SELECT ip, COUNT(*) AS total
    FROM users
    GROUP BY ip
) u2
ON u1.ip = u2.ip
ORDER BY u2.total DESC

点击以下链接查看正在运行的演示:

SQLFiddle

答案 1 :(得分:1)

SELECT ip, username, count(*) total
FROM user_ip
WHERE ip in (
    SELECT ip
    FROM user_ip
    GROUP BY 1
    HAVING count(*) > 1
)
GROUP BY 1,2
ORDER BY 3 DESC,1,2

答案 2 :(得分:1)

您可以尝试:

SELECT `t`.ip, `t`.username, COUNT(`t2`.`id`) total
FROM `test` `t`
LEFT JOIN `test` `t2` ON `t2`.`ip`=`t`.`ip`
GROUP BY `t`.`id`
ORDER BY COUNT(`t2`.`id`) DESC

http://sqlfiddle.com/#!9/e5bb7/1/0