sql-server - SQL 查询需要 20 分钟才能完成,并且只包含 1300 行
问题描述
我有一个具有唯一字符串列和部门描述的表。唯一字符串列的长度代表部门层次结构,因此 4 个字符长度是最低级别,而 2 个字符长度是最高级别。
我的目标是创建新变量,以便我可以显示每一行的层次结构级别和相应的部门描述,并将这些新列用作过滤器
我的 SQL 代码正在运行;但是,为 1300 行表生成结果需要 20 多分钟。
有没有更好的方法来优化这个查询?请注意,我只使用一个表并创建多个副本来创建我想要实现的最终版本。
m.UniqueDescription as "Department Code",
m.DepartmentDescription as "Department",
Left(m.UniqueDescription,2) as "Level 2 Hierarchy",
Left(m.UniqueDescription,3) as "Level 3 Hierarchy",
Left(m.UniqueDescription,4) as "Level 4 Hierarchy",
l2. DepartmentDescription as "L2 Department",
l3. DepartmentDescription as "L3 Department",
l4. DepartmentDescription as "L4 Department"
From department_table m
LEFT JOIN department_table l2
ON Left(m.UniqueDescription,2) = l2.UniqueDescription
LEFT JOIN department_table l3
ON Left(m.UniqueDescription,3) = l3.UniqueDescription
LEFT JOIN department_table l4
ON Left(m.UniqueDescription,4) = l4.UniqueDescription"
以下是我想要实现的输出:
解决方案
首先,数字 ID 的结构和缺失不是一个好习惯
检查索引创建。
ON
不要在or子句的左侧使用函数WHERE
,它不允许执行计划者索引这些列。
而不是FUNCTION(LeftTable.Column) = value
使用LeftTable.Column = INVERSE_FUNCTION(value)
推荐阅读
- python - 如何使用 Google 的 CP-SAT 求解器计算“AddAbsEquality”或“AddMultiplicationEqualit”以进行非线性优化?
- c++ - 错误:数组下标的无效类型“int [int]”|
- python - 在涉及 Return 的 Python 函数中重用逻辑
- javascript - react.component 等效于样式化的组件返回
- wordpress - 如何生成 WordPress 插件“立即更新”网址?
- javascript - 需要暂停一切,直到网络工作者回复消息?
- sql - SAS 联合来自具有相似名称的数据集的不同记录
- python - 未能在 python 中为给定的正整数 n 按预期打印模式
- python - 在 GitLab 中创建 CI/CD 管道以创建可执行文件
- jira-rest-api - 在 java 中使用 REST API 解决 JIRA ISSUE