在多个条件中使用Regexp,SUM和Having子句

时间:2013-07-07 15:45:53

标签: mysql sql

如果我有一张如下表格:

年|工作|技巧| USER_ID

1 | j1; j2 | s1 | 1

2 | j3 | s2 | 1

1 | j1 | s2; s3 | 1

3 | j2 | s1 | 1

当我进行过滤时,我希望

select user_id FROM Table WHERE

1. (Job regexp 'j1' AND TotalYears of Job REGEXP 'j1' >2),

2. (Skill regexp 's1' AND TotalYears of Skill regexp 's1' >3),

首先,我需要找出Job regexp'j1'的总年数以及Skill regexp's1'的总年数。

j1 = 2年,s1 = 4年

如果我只过滤Job regexp'j1',我的查询将是:

SELECT Sum(Years) AS Years,Job AS Job FROM Table WHERE Job REGEXP 'j1' HAVING Years>2;

但现在我需要过滤技能,我应该如何编辑我的查询?

谢谢。

PS:我不确定我的问题标题是否正确,如果内容不合适,请纠正我,谢谢。

编辑(2013-07-10):

我的新表:

TotalWorkYear | JobScope | USER_ID

1 |审计与审计税收;银行/金融;两个| 1

4 |发布;其他; | 1

0 |一般/成本会计;两个| 1

0 | evelen | 1

这是我的疑问:(我离开了加入2个表,成员和成员7,这并不重要)

SELECT Members.user_id,SUM(IF(Members7.JobScope REGEXP 'eve',Members7.TotalWorkYear,0)) yearsJobScope,Members7.JobScope AS JobScope FROM Members LEFT JOIN Members7 ON Members.user_id=Members7.user_id GROUP BY user_id Having JobScope REGEXP 'eve' AND yearsJobScope >= 0

虽然有一行regexp'eve'且totalworkyears是> = 0,但它显示零结果,我认为是由Group By user_id权限引起的,所有记录只根据user_id组成一个。我在那里无论如何要解决它?谢谢。

2 个答案:

答案 0 :(得分:1)

  SELECT user_id,
         SUM(IF(job LIKE '%j1%',years,0)) yearsJob,
         SUM(IF(skill LIKE '%s1%', years,0)) yearsSkill
    FROM yourTable
GROUP BY user_id
  HAVING yearsJob>2
     AND yearsSkill>3;

答案 1 :(得分:1)

尝试以下查询。它会正常工作。

SELECT *
FROM
(
    SELECT USERID
    FROM TABLE_3
    WHERE JOBS LIKE '%j1%'
    GROUP BY USERID 
    HAVING SUM(YEARS) > 0
) AS A
INNER JOIN 
(
    SELECT USERID
    FROM TABLE_3
    WHERE SKILL LIKE '%S1%'
    GROUP BY USERID 
    HAVING SUM(YEARS) > 0

) AS B ON A.USERID = B.USERID    

sqlfiddle