2

我使用 MySQL5.1,并且我有一个表格,我们可以在其中记录有关作业的操作。这是它的架构定义:

CREATE TABLE `actions_log` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `action` varchar(45) DEFAULT NOT NULL,
  `job_id` int(10) unsigned NOT NULL,
  `candidate_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

我需要创建一个请求生成器,以便用户可以使用“AND”和“OR”运算符以及括号搜索表。SQL 请求应返回候选 ID。例如,他们应该能够进行以下搜索:“ActionA OR (ActionB AND ActionC)”。

我使用 UNION 子句来实现这一点,并在提供特定工作时完成工作:

SELECT `candidate_id` FROM (
    SELECT `candidate_id` FROM `actions_log` WHERE `job_id` = 1858 AND `action` = 'a'  
    UNION DISTINCT                                                                            
    (                                                                                         
        SELECT `candidate_id` FROM (
            SELECT `candidate_id`, COUNT(`candidate_id`) AS `count` FROM (
                SELECT DISTINCT `candidate_id` FROM `actions_log` WHERE `job_id` = 1858 AND `action` = 'b'
                UNION ALL                                                                                        
                SELECT DISTINCT `candidate_id` FROM `actions_log` WHERE `job_id` = 1858 AND `action` = 'c'
            ) AS level1
            GROUP BY `candidate_id`
        ) AS level2
        WHERE `count` = 2                                                                                                                              
    )                                                                                                           
) AS candidates;

用户也可以在不指定工作的情况下进行搜索。在这种情况下,任何工作都应该匹配。

这就是问题所在:对于相同的工作,行动必须是有效的结果。例如,使用上面的示例,作业 1 具有“ActionA”,作业 2 具有“(ActionB AND ActionC)”不应是有效匹配。

如果没有指定工作,我无法找到完成这项工作的方法。在这种情况下,也许 UNION 子句不是要走的路。

4

1 回答 1

0

我认为这就足够了:

SELECT candidate_id 
FROM actions_log AS a
WHERE job_id = 1858 
  AND ( action = 'a'  
     OR action = 'b' 
    AND EXISTS 
        ( SELECT candidate_id 
          FROM actions_log 
          WHERE job_id = a.job_id
            AND action = 'c'
        )
      ) ;

或者如果您想将条件分开,以便您可以更轻松地构建更复杂的查询:

    SELECT candidate_id 
    FROM actions_log AS a
    WHERE job_id = 1858 
      AND action = 'a'  
UNION DISTINCT
    SELECT b.candidate_id 
    FROM actions_log AS b
      JOIN actions_log AS c
        ON  c.candidate_id = b.candidate_id
        AND c.job_id = b.job_id
    WHERE b.job_id = 1858 
      AND b.action = 'b'
      AND c.action = 'c' ;
于 2012-09-17T10:02:18.780 回答