Mysql查询1表同一列多次

时间:2013-01-16 23:15:13

标签: mysql

我很生气,希望有人可以帮助我......

我有一张表:

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

现在我正在构建一个搜索查询,用户可以搜索并过滤掉与条件不匹配的人:

搜索示例:Disco,Punk,House

意思是我只想要符合这3个标准的用户(拥有House和Disco和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个人符合此标准......

1 个答案:

答案 0 :(得分: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