我使用2个SQL命令。首先是获取一些参考值,第二个是使用它进行过滤。第一个命令的结果用作:FINISH_TIME和:第二个中的START_TIME。
select FINISHED, STARTED from table
where id = :ID
select * from table
where (FINISHED <= :FINISH_TIME
and
FINISHED >= :START_TIME)
or
(STARTED <= :FINISH_TIME
and
STARTED >= :START_TIME)
or
(STARTED <= :START_TIME
and
FINISHED >= :FINISH_TIME
)
我想结合这两个命令,所以我不必手动将参考值复制到第二个命令。
我找到了这样的解决方案:
FINISHED <= (select FINISHED from table where id = :ID)
但这是多余的。有没有更好的方法来做到这一点,比如将搜索到的值用作变量?
感谢您的帮助!
答案 0 :(得分:0)
您可以使用CTE
执行此操作with TQ as
(
select FINISHED, STARTED from table
where id = :ID
)
select *
from Table1 T1
inner join TQ
on ((T1.FINISHED <= TQ.FINISHED
and T1.FINISHED >= TQ.STARTED)
or ...
答案 1 :(得分:0)
您可以通过一次选择获得具有重叠时间范围的记录。
select t.*
from yourtable t
inner join (
select id, finished, started
from yourtable
where id = :id
) s
on ( t.finished >= s.started
and t.started <= s.finished
and t.started <= t.finished
--and t.id <> s.id
);