有什么方法可以简化这个mysql查询吗?

uz75evzq  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(269)

这里的重点是从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
)
nlejzf6q

nlejzf6q1#

我修改了我的查询以使用not exists和select 1 from user。对于我来说,这两种方法都更快更有效。

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
)

同样的结果,但更干净,只拿出我需要的。

pxy2qtax

pxy2qtax2#

我想您可以通过移动筛选条件来简化查询,如下所示 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

一个示例数据集将有助于验证两个查询的结果

相关问题