我在运行此查询时“错过了右括号错误”
select a.session_id,
a.request_id,
a.timestamp,
a.queue_tag,
b.*
from (select session_id,
request_id,
timestamp,
queue_tag,
(select min(b.timestamp) nextrec
from tbl b
where a.session_id = b.session_id
and a.request_id = b.request_id
and b.timestamp > a.timestamp
and b.is_queue_empty = 0
)
from tbl a
where is_queue_empty = 1
and nullif(queue_name,'') is null
) a
left join tbl b
on a.session_id = b.session_id
and a.request_id = b.request_id
and a.nextrec = b.timestamp
在Oracle中选择这样的列值是否有效?如果不是我在这里缺少的东西?
答案 0 :(得分:3)
我上面的查询工作,不得不移出列别名(由@Martin建议)并删除多余的nullIf()
with tbl as(
select SYSTIMESTAMP+1 timestamp, 0 is_queue_empty , '' queue_name , 'qt' queue_tag, -1 session_id , 1 request_id from dual
union all
select SYSTIMESTAMP timestamp, 1 is_queue_empty , '' queue_name , 'qt1' queue_tag, -1 session_id , 1 request_id from dual
union all
select SYSTIMESTAMP+1 timestamp, 0 is_queue_empty , '' queue_name , 'qt2' queue_tag, -2 session_id , 2 request_id from dual
union all
select SYSTIMESTAMP timestamp, 1 is_queue_empty , '' queue_name , 'qt22' queue_tag, -2 session_id , 2 request_id from dual
)
select a.session_id,a.request_id,a.timestamp,a.queue_tag,
b.*
from
(
select session_id,request_id,timestamp,queue_tag,
(select min(b.timestamp) nextrec
from tbl b
where a.session_id=b.session_id
and a.request_id=b.request_id
and b.timestamp > a.timestamp
and b.is_queue_empty=0) nextrec --> had to put this outside the loop
from tbl a
where is_queue_empty=1 and queue_name is null --in oracle empty string is null thus nullif(queue_name,'') is redundant
) a
left join tbl b on a.session_id=b.session_id
and a.request_id=b.request_id
and a.nextrec = b.timestamp
答案 1 :(得分:0)
您只需在标量子查询后添加别名nextrec。您在该查询中命名,但是当在左连接中加入时,Oracle不知道它的列名。这应该有效:
select a.session_id,
a.request_id,
a.timestamp,
a.queue_tag,
b.*
from (select session_id,
request_id,
timestamp,
queue_tag,
(select min(b.timestamp) nextrec
from tbl b
where a.session_id = b.session_id
and a.request_id = b.request_id
and b.timestamp > a.timestamp
and b.is_queue_empty = 0
) nextrec
from tbl a
where is_queue_empty = 1
and nullif(queue_name,'') is null
) a
left join tbl b
on a.session_id = b.session_id
and a.request_id = b.request_id
and a.nextrec = b.timestamp
此外,当我在Oracle 10g上运行您的原始查询时,我从数据库中收到以下更具描述性的错误:
and a.nextrec = b.timestamp
*
ERROR at line 44:
ORA-00904: "A"."NEXTREC": invalid identifier