Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 合并函数如何在where子句的左侧使用?_Sql_Postgresql - Fatal编程技术网

Sql 合并函数如何在where子句的左侧使用?

Sql 合并函数如何在where子句的左侧使用?,sql,postgresql,Sql,Postgresql,我有以下要优化的查询 SELECT DISTINCT ues.user_id, ues.user_type, ues.owner FROM user_entitled_service ues LEFT JOIN user_resource_group urg

我有以下要优化的查询

                SELECT DISTINCT
                  ues.user_id,
                  ues.user_type,
                  ues.owner
                FROM user_entitled_service ues
                LEFT JOIN user_resource_group urg
                    ON urg.org_id = ues.org_id AND urg.user_id = ues.user_id AND urg.service = ues.service
                INNER JOIN user_assignment ua
                    ON ua.org_id = ues.org_id AND ua.user_id = ues.user_id AND ua.service = ues.service
                WHERE ues.org_id = :orgId AND ues.service = CAST(:service AS service)
                    AND COALESCE(urg.resource_group_id, '') = :resourceGroupId
                    AND NOT EXISTS (
                        SELECT org_id, user_id, service, cluster_id
                        FROM user_discover_state
                        WHERE status = '${UserDiscoverStatus.found}'
                          AND org_id = ues.org_id AND user_id = ues.user_id AND service = ues.service)

我希望能够在资源组id上使用索引,但因为它使用合并函数,所以无法在那里使用索引。我不清楚的是,为什么在左侧使用coalesce,我看到的大多数查询都在右侧使用它,这更有意义,因为我们将列(键)与值匹配,所以在右侧使用它时它是如何工作的?我们可以将其用于索引吗?

在不知道确切数据和查询逻辑的情况下,我无法直接评论
联合
的确切用法。我能做的是重写逻辑,使其变得可搜索(即,可以使用索引):

这就变成了:

AND urg.resource_group_id = :resourceGroupId OR
    urg.resource_group_id IS NULL AND :resourceGroupId = ''

所以resourceGroupId是通过执行此查询的函数参数输入的,但是如果我们执行
urg.resource\u group\u id=:resourceGroupId
,它是否也包括resourceGroupId=''的情况?是的……但这不是您当前的
COALSECE
逻辑,对吗?您的逻辑是当列为null时,参数为空字符串。好的。。。因此,如果我们使用
(urg.resource\u group\u id不为NULL且urg.resource\u group\u id=:resourceGroupId)或(urg.resource\u group\u id为NULL且:resourceGroupId=“”)会更好吗
因为我相信如果我们有一个可空的列,并且我们想要使用index,我们需要通过指定IS not null来确保not null,或者如果我们可以有一个用于合并的索引(resource\u group\u id,”),我没有收到您的评论。在任何情况下,我给出的版本都不会在条件中使用任何函数,理论上应该是索引的候选。
AND urg.resource_group_id = :resourceGroupId OR
    urg.resource_group_id IS NULL AND :resourceGroupId = ''