I'm going crazy on this hope someone can help me out....
I have one Table:
user_skils:
ID | UID | SKILL
1 23 House
2 5 Disco
3 8 Punk
... ... ...
... ... ...
... ... ...
Now Im building a search query where the user can search and filter out people that don't match the criteria:
Example Search: Disco, Punk, House
Meaning that I only want the users that match this 3 criterias ( have House AND Disco AND PUNK)... How can I manage this via a query?
Something like
SELECT count(uid) as matches ,
GROUP_CONCAT(skill) as skills_grouped
FROM user_skilks
WHERE skill LIKE %Disco%
AND skill LIKE %punk%
AND skill LIKE %house%
Should give me something like:
Matches | skills_grouped
3 House,Punk,Disco
Meaning that 3 people match this criteria...
Group your table by UID
and then filter the resulting groups (ie using the HAVING
clause) for those of interest:
SELECT UID
FROM user_skils
GROUP BY UID
HAVING SUM(SKILL LIKE '%House%')
AND SUM(SKILL LIKE '%Disco%')
AND SUM(SKILL LIKE '%Punk%' )
This works in MySQL because it does not have true boolean types. In other RDBMS, you would have to use a CASE
expression:
HAVING SUM(CASE WHEN SKILL LIKE '%House%' THEN 1 ELSE 0 END) > 0
AND ...
To get the number of such users, group the results again:
SELECT COUNT(*) FROM (
SELECT 1
FROM user_skils
GROUP BY UID
HAVING SUM(SKILL LIKE '%House%')
AND SUM(SKILL LIKE '%Disco%')
AND SUM(SKILL LIKE '%Punk%' )
) t
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.