How to check if a specific country code exists in a cell with MySQL?

MySQLMySQLi Database

For specific value, use FIND_IN_SET(). Let us first create a −

mysql> create table DemoTable1439
   -> (
   -> CountryId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> CountryCode varchar(20)
   -> );
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1439(CountryCode) values('1022_US,7894_UK');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1439(CountryCode) values('6567_AUS,7894_UK');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1439(CountryCode) values('6567_AUS');
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select −

mysql> select * from DemoTable1439;

This will produce the following output −

+-----------+------------------+
| CountryId | CountryCode      |
+-----------+------------------+
|         1 | 1022_US,7894_UK  |
|         2 | 6567_AUS,7894_UK |
|         3 | 6567_AUS         |
+-----------+------------------+
3 rows in set (0.00 sec)

Following is the query to check if country code exists in a cell −

mysql> select * from DemoTable1439
   -> where find_in_set('6567_AUS',CountryCode) > 0;

This will produce the following output −

+-----------+------------------+
| CountryId | CountryCode      |
+-----------+------------------+
|         2 | 6567_AUS,7894_UK |
|         3 | 6567_AUS         |
+-----------+------------------+
2 rows in set (0.00 sec)
raja
Published on 12-Nov-2019 11:24:08
Advertisements