进行查询以按IP分组

时间:2016-04-14 06:40:10

标签: mysql

我有一个查询问题,想知道这是否可以查询。 在我提出问题的数据库看起来像这样:

-------------------------------------------
id  |  name       |        IP      |   nr
-------------------------------------------
 1  | Fleet-1234  | 192.168.52.254 | 1234
 5  | Boat-4567   | 192.168.52.256 | NULL
 9  | Boat-4565   | 192.168.52.250 | NULL
10  | Boat-4547   | 192.168.52.252 | NULL
13  | Fleet-6663  | 192.168.44.256 | 6663
18  | Boat-2345   | 192.168.44.145 | NULL
56  | Boat-2345   | 192.168.44.14  | NULL
60  | Boat-1111   | 192.168.44.15  | NULL

我希望的结果是:

-------------------------------------------
id  |  name       |        IP      |   nr
-------------------------------------------
 1  | Fleet-1234  | 192.168.52.254 | 1234
 5  | Boat-4567   | 192.168.52.256 | 1234
 9  | Boat-4565   | 192.168.52.250 | 1234
10  | Boat-4547   | 192.168.52.252 | 1234
13  | Fleet-6663  | 192.168.44.256 | 6663
18  | Boat-2345   | 192.168.44.145 | 6663
56  | Boat-2345   | 192.168.44.14  | 6663
60  | Boat-1111   | 192.168.44.15  | 6663

我认为我需要做的是: - 比较IP的前3个八位字节(相同的#34;车队") -iff比较被发现使用" nr"来自舰队-XXXX的colum在同一"组"

我真的不知道这是否可行以及如何做到这一点。 是否有人可以帮助我查询此查询?

2 个答案:

答案 0 :(得分:1)

请参阅sqlfiddle

SELECT 
    t0.id
    , t0.name
    , t0.IP
    , t1.nr
FROM your_table t0
INNER JOIN (SELECT LEFT(IP, LENGTH(IP) - LOCATE('.', REVERSE(IP))) AS shortened_IP, MAX(nr) AS nr FROM your_table GROUP BY 1) t1
ON LEFT(IP, LENGTH(IP) - LOCATE('.', REVERSE(IP))) = t1.shortened_IP;

答案 1 :(得分:0)

使用substr和group by

select substr(IP, LOCATE('.', REVERSE(IP))+1, 3) as ip_base, count(*)
from your_table 
group by ip_base;