Reputation: 1926
I'm trying to check if a country code exists in a cell country
before a user can add anything to the database. So, if a country code did not exist, he would not be able to add anything.
I'm storing country codes as comma separated values. The column type is VARCHAR.
"id" "rtype" "country"
"1" "0" "US,UK,SE,CA"
"2" "1" "US"
"3" "2" "UK"
I ran the following query, but this results in no rows. Where am going wrong here? The problem is, this query needs to run with comma separated values as well as single values.
select id, rtype from test where id=1 and country in('US')
Expected results
id | rType
1 | 0
select id, rtype from test where id=2 and country in('US')
Expected results
id | rType
2 | 0
Upvotes: 2
Views: 590
Reputation: 39243
MySQL has a really nice Set Datatype. It is very efficient and can store till 64 distinct members of 255 values. I don't know if you could change your column type, but it would solve a lot of problems:
You'd search using the FIND_IN_SET function.
Upvotes: 1
Reputation: 1
Since the country codes are the comma separated values , you can not directly use in . You can you like instead.
select id, rtype from test where country like '%US%'
Upvotes: 0
Reputation: 43434
Try this out:
SELECT id, rtype FROM test
WHERE FIND_IN_SET('US', country) > 0
This is how the FIND_IN_SET(str,strlist)
function works:
Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. [...] Returns 0 if str is not in strlist or if strlist is the empty string.
Upvotes: 3