用于匹配同一列中的多个值的SQL查询

时间:2013-05-24 07:26:54

标签: mysql

我在MySQL中有一个表如下。

Id   Designation           Years          Employee
1    Soft.Egr            2000-2005           A
2    Soft.Egr            2000-2005           B
3    Soft.Egr            2000-2005           C
4    Sr.Soft.Egr         2005-2010           A
5    Sr.Soft.Egr         2005-2010           B
6    Pro.Mgr             2010-2012           A

我需要让那些担任Soft.Egr和Sr.Soft.Egr以及Pro.Mgr的员工。在查询中无法使用IN或多个AND。这该怎么做??

5 个答案:

答案 0 :(得分:24)

一种方式:

select Employee
from job_history
where Designation in ('Soft.Egr','Sr.Soft.Egr','Pro.Mgr')
group by Employee
having count(distinct Designation) = 3

答案 1 :(得分:6)

你可能真正想要的是relational division,即使你的运动要求禁止使用AND(无论出于何种原因?)。这很棘手,但可以在SQL中正确表达。

prosa中的关系划分意味着:查找在employees表中为所有现有指定创建记录的员工。或者在SQL中:

SELECT DISTINCT E1.Employee FROM Employees E1
WHERE NOT EXISTS (
    SELECT 1 FROM Employees E2
    WHERE NOT EXISTS (
        SELECT 1 FROM Employees E3
        WHERE E3.Employee = E1.Employee
        AND E3.Designation = E2.Designation
    )
)

要查看上述查询的实际效果,请考虑此SQLFiddle

可以在此处找到解释关系划分的良好资源: http://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division

答案 2 :(得分:3)

如果您需要获取有关每个角色(如日期)的其他信息,那么为每个其他名称加入回原始表是一个可能的解决方案:

SELECT t.Employee, t.Designation, t.Years, t1.Designation, t1.Years, t2.Designation, t2.Years
FROM Table t
INNER JOIN t2 ON (t2.Employee = t.Employee AND t2.Designation = 'Sr.Soft.Egr')
INNER JOIN t3 ON (t3.Employee = t.Employee AND t3.Designation = 'Soft.Egr')
WHERE t.Designation = 'Pro.Mgr';

答案 3 :(得分:1)

为什么不是以下(对于postgresql)?

SELECT employee FROM Employees WHERE Designation ='Sr.Soft.Egr'
INTERSECT 
SELECT employee FROM Employees WHERE Designation ='Soft.Egr'
INTERSECT 
SELECT employee FROM Employees WHERE Designation ='Pro.Mgr'

链接到SQLfiddle

我知道这可能没有优化,但我发现这更容易理解和修改。

答案 4 :(得分:0)

尝试此查询:

SELECT DISTINCT t1.employee, 
                t1.designation 
FROM tempEmployees t1, tempEmployees t2, tempEmployees t3 
WHERE t1.employee = t2.employee AND
      t2.employee = t3.employee AND 
      t3.employee = t1.employee AND
      t1.designation != t2.designation AND 
      t2.designation != t3.designation AND 
      t3.designation != t1.designation