0

我疯了,希望有人能帮助我......

我有一张桌子:

user_skils:
ID  | UID | SKILL
1     23    House
2     5    Disco
3     8    Punk
...  ...    ...
...  ...    ...
...  ...    ...

现在我正在构建一个搜索查询,用户可以在其中搜索并过滤掉不符合条件的人:

示例搜索:迪斯科、朋克、豪斯

这意味着我只想要符合这 3 个条件的用户(有 House AND Disco AND PUNK)......我如何通过查询来管理这个?

就像是

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%

应该给我类似的东西:

Matches | skills_grouped
3         House,Punk,Disco

这意味着有 3 人符合此条件...

4

1 回答 1

1

对您的表进行分组UID,然后HAVING为感兴趣的组过滤结果组(即使用子句):

SELECT   UID
FROM     user_skils
GROUP BY UID
HAVING   SUM(SKILL LIKE '%House%')
     AND SUM(SKILL LIKE '%Disco%')
     AND SUM(SKILL LIKE '%Punk%' )

这在 MySQL 中有效,因为它没有真正的布尔类型。在其他 RDBMS 中,您必须使用CASE表达式:

HAVING   SUM(CASE WHEN SKILL LIKE '%House%' THEN 1 ELSE 0 END) > 0
     AND ...

要获取此类用户的数量,请再次对结果进行分组:

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
于 2013-01-16T23:26:35.900 回答