这里的要点是从users表中获取尚未分配给特定组织的子用户。但是,如果将子用户分配给当前用户,则仍然包括它。
它有效,但我觉得语法可能更简单:
SELECT u.userId, u.firstName, u.lastName, u.username, u2.services_user_id
FROM user u
LEFT JOIN user u2 ON u.userId = u2.services_user_id
WHERE u.enabled = 1
AND u.organization_id = 1
AND u.userId NOT IN (
SELECT services_user_id FROM user
WHERE organization_id = 2
AND services_user_id <> 19
AND services_user_id IS NOT NULL
)
答案 0 :(得分:0)
我想您可以通过在on
子句
SELECT u.userId, u.firstName, u.lastName, u.username, u2.services_user_id
FROM user u
LEFT JOIN user u2 ON u.userId = u2.services_user_id
AND (u2.organization_id <> 2 OR u2.services_user_id = 19)
WHERE u.enabled = 1
AND u.organization_id = 1
示例数据集有助于验证两个查询的结果
答案 1 :(得分:0)
我重写了我的查询以使用NOT EXISTS和SELECT 1 FROM用户。对于我的目的,这两者都更快,更有效。
SELECT u.userId, u.firstName, u.lastName, u.username
FROM user u
LEFT JOIN user u2 ON u.userId = u2.services_user_id
WHERE u.enabled = 1
AND u.organization_id = 14
AND NOT EXISTS (
SELECT 1 FROM user u3
WHERE
u3.organization_id = 1
AND u3.services_user_id <> 19
AND u3.services_user_id IS NOT NULL
AND u.userId = u3.services_user_id
)
结果相同,但更干净,只能拉出我需要的东西。