1

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

3
  • Please check your spelling before posting questions. Commented Feb 18, 2013 at 10:28
  • @Martin Bean, Thank you so much for your advice. I will keep it in my mind wherever I will post any question Commented Feb 18, 2013 at 11:36
  • What is the type of the country column? Commented Mar 1, 2013 at 10:00

6 Answers 6

2

You can use FIND_IN_SET function, for example -

SELECT * FROM table
WHERE FIND_IN_SET('US', country) ;
Sign up to request clarification or add additional context in comments.

1 Comment

in inner join conditions SELECT * FROM table1 t1 INNER JOIN table2 t2 ON FIND_IN_SET(t2.id, t1.column2)
2

You can use FIND_IN_SET function, for example -

 SELECT * FROM table WHERE FIND_IN_SET('US', country) ;

Comments

1
SELECT id, country
FROM yourtable
WHERE FIND_IN_SET('US', country)

or

SELECT id, country
FROM yourtable
WHERE CONCAT(',', country, ',') LIKE '%,US,%'

Please see fiddle here.

Comments

1
SELECT  *
FROM    tableName
WHERE   FIND_IN_SET('US', country) > 0

Comments

1

Try the below code.

SELECT ID,COUNTRY FROM TABLE_NAME
WHERE COUNTRY LIKE '%US%;

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.