在1列

时间:2018-02-22 16:11:06

标签: mysql

为简单起见,假设产品是工作板 - 使用工作板的人可以通过多个过滤器过滤作业,例如位置,功能,技能,关键词等。

我正在尝试创建一个查询,从表中选择与用户过滤条件匹配的唯一作业。

麻烦似乎是将多个OR运算符与多个AND运算符组合在一起。我想这个表可能设置不正确。

使用下表作为一个非常简单的例子, 我希望看到有

的乔布斯
Location = London OR Manchester
AND
Function = Marketing OR Sales
AND 
Keyword  = SEO 

Note: Location, Function and Keyword are not Groups, they are the 
filter of the user searching the jobs (maybe that is the problem?)

JobId   | Group                   | Value
1       | LocationJob             | London
1       | LocationCovered         | Leeds
1       | FunctionJob             | Tech
1       | FunctionJob2            | Engineering
1       | SkillRequired           | PHP
1       | SkillOptional           | Python
2       | LocationJob             | Newcastle
2       | LocationCovered         | Manchester
2       | FunctionJob             | SEO
2       | FunctionJob2            | PPC
2       | SkillRequired           | Marketing
3       | LocationJob             | Manchester
3       | LocationCovered         | Leeds
3       | FunctionJob             | Sales
3       | FunctionJob2            | Business Development
3       | SkillRequired           | SEO

结果应该是作业2和3

我目前正在进行以下操作,但是我有成千上万的记录,所以如果有很多连接,它可能会非常慢..

SELECT TKeywords.UserID
FROM `Search` TKeywords
  JOIN `Search` TFunctions ON TKeywords.UserID = TFunctions.UserID AND 
       TFunctions.Value IN ('Function1', 'Function2','Function3')
  JOIN `Search` TSkills ON TKeywords.UserID = TSkills.UserID AND 
       TSkills.Value IN ('Skills1', 'Skills2','Skills3')
  JOIN `Search` TLocation ON TKeywords.UserID = TLocation.UserID AND 
       TLocation.Value IN ('Location1', 'Location2','Location3')
WHERE TKeywords.Value IN ('Keyword1', 'Keyword2', 'Keyword3')

任何帮助非常感谢。感谢

2 个答案:

答案 0 :(得分:1)

这应该有效:

select s1.UserId from search s1
join (
    select UserId from search 
    where Group = 'Industry' and Value = 'Construction'
) s2 on s1.UserId = s2.UserId
where Group = 'Skill' and Value in('PHP', 'Python')

答案 1 :(得分:0)

选项之一是使用group by和sum来验证。

SELECT 
 Userid
FROM 
 [table]
GROUP BY 
 Userid
HAVING 
(
     SUM(`Group` = 'Skill') AND SUM(Value = 'PHP')
   OR
     SUM(`Group` = 'Skill') AND SUM(Value = 'Python')
) 
 AND
(
  SUM(`Group`) = 'Industry' AND SUM(Value = 'Construction')
)

demo http://www.sqlfiddle.com/#!9/a6034/2