首页 > 解决方案 > 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"


以下是我想要实现的输出:

表格格式

标签: sql-server

解决方案


首先,数字 ID 的结构和缺失不是一个好习惯

检查索引创建。

ON不要在or子句的左侧使用函数WHERE,它不允许执行计划者索引这些列。

而不是FUNCTION(LeftTable.Column) = value使用LeftTable.Column = INVERSE_FUNCTION(value)


推荐阅读