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

问题描述 投票:0回答:1

我有一个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百万个条目。

sql database sqlite
1个回答
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)上的索引开始。

© www.soinside.com 2019 - 2024. All rights reserved.