SQLite:如何获取匹配的IN列表和另一个列表

cdmah0mi  于 2023-03-23  发布在  SQLite
关注(0)|答案(2)|浏览(349)

我有三张table:
Employee (id, name)
Department (id, name)
DepartmentLink (id, employeeId, departmentId)
我正在尝试编写一个查询,该查询的结果是在列表A中至少有一个departmentId,并且在列表B中至少有一个departmentId。
我试过了,但没有结果:

SELECT
    Employee.id,
    DepartmentLink.departmentId
FROM DepartmentLink 
INNER JOIN Employee ON DepartmentLink.employeeId == Employee .id
WHERE DepartmentLink.departmentId IN (1,2,3)
AND DepartmentLink.departmentId IN (100)

结果应该是部门(1或2或3)和100中的Employee(或只是ID)。
这在SQLite中可能吗?

vfwfrxfs

vfwfrxfs1#

使用INTERSECT ...

SELECT employeeId
FROM departmentLink
WHERE departmentId in (1, 2, 3)
INTERSECT
SELECT employeeId
FROM departmentLink
WHERE departmentId in (100)
umuewwlo

umuewwlo2#

可以使用两个exists条件:

SELECT e.id,
FROM   Employee e
WHERE  EXISTS (SELECT *
               FROM   DepartmentLink d1
               WHERE  d1.employeeId = e.id AND departmentId IN (1,2,3)) AND
       EXISTS (SELECT *
               FROM   DepartmentLink d2
               WHERE  d2.employeeId = e.id AND departmentId = 100)

相关问题