SQLite |从两个(模式)相同的表中检索数据

时间:2017-12-19 12:14:53

标签: sql database sqlite

我有一个SQLite Database,我在其中使用以下query从两个表中获取数据。

select ie.* 
from (select * 
      from History where Station = @station and TimeStampCome <= @till and TimeStampCome >= @from 
      union all 
      select * 
      from Pending where Station = @station and TimeStampCome <= @till and TimeStampCome >= @from
     ) ie 
order by TimeStampCome desc LIMIT 100 OFFSET 1

这是最好和最有效的方式吗?我已将alarm objects存储在database中。因此,可以轻松地输入超过1百万个条目。

1 个答案:

答案 0 :(得分:1)

对于您的特定查询,最好先限制每个表中的行,如下所示:

with h as (
      select h.*
      from history h
      where Station = @station and TimeStampCome <= @till and TimeStampCome >= @from 
      order by TimeStampCome desc
      limit 101
     ),
     p as (
      select p.*
      from pending p
      where Station = @station and TimeStampCome <= @till and TimeStampCome >= @from 
      order by TimeStampCome desc
      limit 101
     )
select pe.*
from (select h.* from h union all
      select p.* from p
     ) pe
order by TimeStampCome desc
limit 100 offset 1;

但是,如果您开始使用不同的偏移量,这就变得不太可行了。

请注意,如果需要考虑性能,请从两个表中(Station, TimeStampCome)的索引开始。