Reputation: 438
I want to search countries from a table as given below:
+-----+-------------+
| id | country
+-----+-------------+
| 1 | US
+-----+-------------+
| 2 | US,IN,UK
| 3 | US,NZ
| 4 | AUS
How I perform sql query to get all records containing a country = 'US' with additional comma separated countries?
Thanks
Upvotes: 1
Views: 1906
Reputation: 109
You can use FIND_IN_SET function, for example -
SELECT * FROM table WHERE FIND_IN_SET('US', country) ;
Upvotes: 2
Reputation: 5236
You may use LIKE
or RLIKE
for this.
SELECT * FROM table_name WHERE country RLIKE '(.+?,)*?US(,.+?)*'
or
SELECT * FROM table_name WHERE country LIKE '%US%'
First query avoids retrieval of ones with country having US as substring like RUS
SELECT * FROM table_name WHERE country RLIKE '(.+,)(.+,)*?US(,.+)*|(.+,)*?US(,.+)(,.+)*'
selects only those with at least another entry along with US.
Upvotes: 1
Reputation: 121902
You can use FIND_IN_SET function, for example -
SELECT * FROM table
WHERE FIND_IN_SET('US', country) ;
Upvotes: 2
Reputation: 2415
Try the below code.
SELECT ID,COUNTRY FROM TABLE_NAME
WHERE COUNTRY LIKE '%US%;
Upvotes: 1