【问题标题】:How to speed up this oracle select query?如何加快这个 oracle 选择查询?
【发布时间】:2025-12-29 22:35:07
【问题描述】:

我在代码中有以下 sql 查询,这使得查询变慢:

SELECT a.*,
         (SELECT CASE
                    WHEN (score IS NOT NULL OR comments IS NOT NULL)
                    THEN
                       ' ( score : ' || TO_CHAR (SCORE) || ' )'
                    ELSE
                       ' ( hələ )'
                 END
            FROM t_lecture_task_present b
           WHERE b.t_idx = a.t_idx AND B.STUDENT_ID = '{$member_code}')
            AS task_score
    FROM t_lecture_task a
   WHERE a.lec_open_idx = '24422'
ORDER BY s_date ASC, t_idx ASC

(16 秒)

如果我在没有

的情况下尝试查询
(SELECT CASE
           WHEN (score IS NOT NULL OR comments IS NOT NULL)
           THEN
              ' ( score : ' || TO_CHAR (SCORE) || ' )'
           ELSE
              ' ( hələ )'
        END
   FROM t_lecture_task_present b
  WHERE b.t_idx = a.t_idx AND B.STUDENT_ID = '{$member_code}')
 as task_score

它工作得更快。

所以,我尝试删除 or comments is not null,它的运行速度快了 2 秒。

【问题讨论】:

  • 你检查过表索引吗?

标签: oracle select subquery where-clause


【解决方案1】:

您无法比较产生不同结果的查询的性能:)

根据表中的数据分布,您可能会从这些索引中受益:

t_lecture_task(lec_open_idx) 
t_lecture_task_present(t_idx, student_id)

尝试重新编写查询以使用联接而不是标量子查询(选择为列)。它们不仅难以阅读,而且更难优化。

select a.*
      ,case when score    is not null 
              or comments is not null then ' ( score : ' || to_char (score) || ' )'
                                      else ' ( hələ )'
        end as task_score
  from t_lecture_task a
  left join t_lecture_task_present b on(
       b.t_idx      = a.t_idx
   and b.student_id = '{$member_code}')
  )
 where a.lec_open_idx = '24422';

【讨论】:

  • 谢谢,我会在星期一尝试测试一下,并写下发生了什么:)
  • @DenisSamadov,对你有用吗?如果是这样,请考虑接受答案:)
  • 不,这并没有很多工作,所以我创建了新页面只是为了“t_lecture_task_present”选择,并通过ajax调用它。速度更快,更好看