我认为我会从一个子查询开始,生成(不相交的)联合:
- A company ID and a (non-zero) count of the users that can access the system where at least one user can access the system
- A company ID and a zero count when no user can access the system
假设 User.CanAccessSystem IS NULL
是为了考虑到左连接而需要的因素,那么就会导致:
SELECT Company.ID, COUNT(*) AS UserCount
FROM Company, User
WHERE Company.ID = User.CompanyID
AND User.CanAccessSystem = true
UNION
SELECT Company.ID, 0 AS UserCount
FROM Company
WHERE NOT EXISTS (SELECT * FROM User
WHERE Company.ID = User.CompanyID
AND User.CanAccessSystem = true)
您可以使用 AND Company.CanAccessSystem = true 过滤两个部分,如果大多数公司无法访问系统,则可能会有益处-或者您可以推迟到最终处理阶段。
然后,您需要将此结果与公司进行直接连接,确保公司能够访问系统的过滤条件在该线路的某个地方应用。
从名义上来看,这将导致以下(尚未测试的)代码:
SELECT UserCount, Company.*
FROM Company JOIN
(SELECT Company.ID AS ID, COUNT(*) AS UserCount
FROM Company, User
WHERE Company.ID = User.CompanyID
AND User.CanAccessSystem = true
UNION
SELECT Company.ID AS ID, 0 AS UserCount
FROM Company
WHERE NOT EXISTS (SELECT * FROM User
WHERE Company.ID = User.CompanyID
AND User.CanAccessSystem = true)
) AS NumUsers
ON Company.ID = NumUsers.ID
WHERE Company.CanAccessSystem = true