2015-11-04 68 views
3

說我有一個數據集如下所示:MySQL的「和」的結果中的邏輯設置

table foo 

id | employeeType | employeeID 
------------------------- 
1 | Developer | 1 
2 | Developer | 2 
3 | Developer | 3 
4 | Manager  | 1 
5 | Manager  | 4 
6 | Manager  | 5 
7 | CEO   | 1 
8 | CEO   | 6 

,我想如果有能力運行,將返回所有的employeeids(與employeeTypes一起)查詢所有員工類型之間的普通員工ID(即'和'邏輯,具有所有員工類型的ONLY員工ID將會返回,employeeType = Developer和employeeType = Manager和employeeType = CEO)。對於上面的例子中輸出的數據將是

result table 

id | employeeType | employeeID 
------------------------- 
1 | Developer | 1 
4 | Manager  | 1 
7 | CEO   | 1 

我能做到這一點時,我只用了只有兩個employeeTypes自行加入表是這樣的。

select * from foo as fooOne 
join foo as fooTwo 
on fooOne.employeeID = fooTwo.employeeID 
AND 
fooOne.employeeType <> fooTwo.employeeType 

該查詢返回的值從fooTwo結果集的「和」邏輯相匹配的時候,但同樣,只有兩種類型的員工。我真正的用例場景表明我需要能夠處理可變數量的employeeTypes(3,4,5等)。

任何想法都將不勝感激。

回答

1

這應該返回所需的行:

SELECT foo.* 
FROM 
    foo 
WHERE 
    employeeID IN (
    SELECT employeeID 
    FROM foo 
    GROUP BY employeeID 
    HAVING COUNT(DISTINCT employeeType) = 
     (SELECT COUNT(DISTINCT employeeType) 
     FROM foo) 
) 

請看到fiddle here

內查詢將返回不同的員工類型的數量:

(SELECT COUNT(DISTINCT employeeType) FROM foo) 

中間的查詢將返回所有員工類型的最大數目的所有員工ID:

SELECT employeeID 
FROM foo 
GROUP BY employeeID 
HAVING COUNT(DISTINCT employeeType) = 
     (SELECT COUNT(DISTINCT employeeType) FROM foo) 

和外部查詢將返回整個行。

+0

哇!很棒。非常感謝,小提琴也超越了。再次感謝。 – Josh

1

我同意這可能會被視爲一種非常低效率的做法,但這應該仍然可以完成工作。坦率地說,我看不出有其他辦法。

SELECT * FROM (
    SELECT EMPLOYEE_ID, GROUP_CONCAT(DISTINCT EmployeeType ORDER BY EmployeeType) AS Roles 
    FROM EMPLOYEES GROUP BY EMPLOYEE_ID 
) EMPLOYEE_ROLES 
WHERE EMPLOYEE_ROLES.Roles = 'CEO,Developer,Manager'; 

請注意,最後提供的逗號分隔的角色列表按字母順序排列。

+0

看起來它也能工作。謝謝:) – Josh

1

你可以嘗試一個子查詢,使其動態

SELECT employeeID, employeeType 
FROM foo 
WHERE employeeID IN (
SELECT employeeID 
FROM foo 
GROUP BY employeeID 
HAVING COUNT(DISTINCT employeeType) = (SELECT COUNT(DISTINCT employeeType) FROM foo) 
) 
+0

啊是的...這是非常有意義的。謝謝! – Josh