假设我有如下数据集:
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)的查询,其中所有employeeTypes之间都有一个共同的员工ID(即'和'逻辑。具有所有employeeTypes的所有employeeID将返回。 = 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等等)
对此的任何想法都将不胜感激。
答案 0 :(得分: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';
请注意,最后提供的以逗号分隔的角色列表按字母顺序排列。
答案 1 :(得分: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)
)
答案 2 :(得分: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)
并且外部查询将返回整行。