MySQL中進行MySQL字串操作以僅計算IP地址記錄中的重複值的子部分?
對於這種字串操作,需要使用MySQL SUBSTRING_INDEX()。首先建立一個表 −
mysql> create table DemoTable ( SystemIpAddress text ); Query OK, 0 rows affected (0.58 sec)
使用insert命令在表中插入一些記錄 −
mysql> insert into DemoTable values('192.168.130.67'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values('192.168.130.87'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('192.168.131.47'); Query OK, 1 row affected (0.31 sec) mysql> insert into DemoTable values('192.168.134.50'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('192.168.131.12'); Query OK, 1 row affected (0.21 sec)
使用select語句顯示錶中的所有記錄 −
mysql> select *from DemoTable ;
這將產生以下輸出 −
+-----------------+ | SystemIpAddress | +-----------------+ | 192.168.130.67 | | 192.168.130.87 | | 192.168.131.47 | | 192.168.134.50 | | 192.168.131.12 | +-----------------+ 5 rows in set (0.00 sec)
以下是IP地址記錄中進行字串操作的查詢 −
mysql> select substring_index(tbl.SystemIpAddress, '.', 3) , count(*) as Total from DemoTable tbl group by substring_index(tbl.SystemIpAddress, '.', 3) order by Total desc limit 5;
這將產生以下輸出 −
+----------------------------------------------+-------+ | substring_index(tbl.SystemIpAddress, '.', 3) | Total | +----------------------------------------------+-------+ | 192.168.130 | 2 | | 192.168.131 | 2 | | 192.168.134 | 1 | +----------------------------------------------+-------+ 3 rows in set (0.00 sec)
廣告