20

我在 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。这个怎么做??

4

5 回答 5

43

单程:

select Employee
from job_history
where Designation in ('Soft.Egr','Sr.Soft.Egr','Pro.Mgr')
group by Employee
having count(distinct Designation) = 3
于 2013-05-24T07:32:12.077 回答
10

您实际上可能正在寻找的是关系除法,即使您的锻炼要求禁止使用AND(无论出于何种原因?)。这很棘手,但可以在 SQL 中正确表达。

prosa 中的关系划分意味着:查找那些在员工表中具有所有现有名称记录的员工。或者在 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

于 2013-05-24T07:37:27.590 回答
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';
于 2013-05-24T07:34:56.210 回答
2

为什么不是以下(对于 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

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

于 2015-10-13T23:04:07.820 回答
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
于 2018-04-26T06:07:01.377 回答