2

我必须按某列整理我的数据,以便首先出现某个特定值。所以对于这样的查询......

  SELECT rtrim(taskid) into v_taskid FROM tasks
  where
    /* some where clausers */
  and rownum = 1

...我基于它case when,但困扰我的是我现在拥有的三个嵌套选择:

  SELECT rtrim(taskid) into v_taskid FROM tasks where taskid in (
    select taskid from (
        select taskid,
        case when taskuser like '%myuser%' 
       then 0
           else 100
        end as ordervalue
        FROM tasks
        where       
          /* some where clausers */
        order by ordervalue
        )
    )    
    and rownum = 1

性能方面,我认为这应该不是问题,但它看起来有点像意大利面条......有什么办法可以放入case-when条款中where吗?

4

3 回答 3

3

您正在查询该tasks表两次。这不是必需的,会使您的查询运行缓慢。您的查询可以组合成一个简单的查询,如下所示:

SELECT rtrim(taskid) into v_taskid
FROM (
  SELECT taskid 
  FROM tasks 
  WHERE /* some where clauses */
  ORDER BY case when taskuser like '%myuser%' then 0 else 100 end
)
WHERE rownum = 1;

然后要么只检索第一行,要么在外部查询中添加 rownum 部分。

于 2010-03-11T13:03:11.607 回答
1

用户row_number() over (...)

select 
  taskid
from (
  select 
    taskid,
    row_number() over (
      order by 
        case when taskuser like '%myuser%' then  0 
                                           else 100 
      end
    ) r
  from
    tasks
  WHERE
    /* some where clausers */
)
where 
  r = 1;
于 2010-03-11T12:54:57.930 回答
1

如果taskidtasks你的主键不需要自加入(外部选择):

SELECT rtrim(taskid)
  FROM (SELECT taskid
           FROM tasks
           /* where clause */
          ORDER BY CASE
                      WHEN taskuser LIKE '%myuser%' THEN
                       0
                      ELSE
                       100
                   END)
 WHERE ROWNUM = 1
于 2010-03-11T12:58:28.527 回答