i am having a database in that 'users' table contain 4 fields id , name , gender , language
ex. (database entries)
1 jhon male en-sp-gr
2 mira female sp-
3 mike male en-
4 shel female sp-gr
etc...
here en,sp,gr are languages English , Spanish , German what i am trying to fetch the count of users who speaks only en,sp (english and spanish languages) the database contains more than 300 users and i am more more confused how to get the count of users who speaks only en and sp the language field of the table contains string
en-sp-gr
how can i omit -gr and hyphen ( - ) form the string and this only for one row i have to perform this for each row and then count of those users only who speaks en and sp. i am not expert in sql :(
You could do something like this:
SELECT *
FROM users
WHERE language IN ('en-sp', 'sp-en')
However, you really should look into normalizing your database:
Users
ID|Name|Gender
Languages
ID|Code
User_Language_Map
UserID|LanguageID
Then you could do something like this:
SELECT *
FROM Users
WHERE ID IN
(
SELECT UserID
FROM User_Language_Map
WHERE LanguageID IN (IDFORSP, IDFORGR)
GROUP BY UserID
HAVING COUNT(DISTINCT LanguageID) = 2
)
If you cannot do that, and the language filter is going to be dynamic, then you really would need to create a function that will create the appropriate string combinations (or you could build a regex on the fly) and pass that into your IN
. Otherwise, I don't know that you have many options as you are parsing strings at that point.
This is why you should not store multiple values in one field. They should be stored in a normalized table instead.
But you can accomplish this by replacing the -
with ,
and using FIND_IN_SET()
. This is necessary because FIND_IN_SET()
expects a comma-separated list of values. This can only be reasonably managed with a handful of languages though, since you need to code all the permutations into the query. For this reason (among others like indexing) it is very strongly recommended to refactor this into a related table linking users to their spoken languages.
SELECT COUNT(*) FROM users
WHERE
FIND_IN_SET('en', REPLACE(language,'-',',')) > 0
AND FIND_IN_SET('sp', REPLACE(language,'-',',')) > 0
AND FIND_IN_SET('gr', REPLACE(language,'-',',')) = 0
SELECT
count(case when language = 'en' then language end) as English,
count(case when language = 'sp' then language end) as Spanish
FROM users
In above query can count the English Language Users and Spanish Laguage User.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.