MySQL string manipulation to count only sub-part of duplicate values in IP ADDRESS records?

MySQLMySQLi Database

For such string manipulations, you need to use MySQL SUBSTRING_INDEX(). Let us first create a table −

mysql> create table DemoTable
(
   SystemIpAddress text
);
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

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)

Display all records from the table using select statement −

mysql> select *from DemoTable ;

This will produce the following output −

+-----------------+
| 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)

Following is the query for string manipulation on IP Address records −

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;

This will produce the following output −

+----------------------------------------------+-------+
| 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)
raja
Published on 07-Oct-2019 11:39:07
Advertisements