首页 > 解决方案 > 高效查询和保存布尔列的最近日期

问题描述

我有一个保存日期的表格,事情是在日期之后由一个布尔值完成的。我需要对此进行查询以运行报告,该报告告诉我每个最新列的完成日期。所以表格看起来像这样:

id item date        sweep dust vacuum wash
1   1   2021-01-01    t
2   1   2021-02-02          t      
3   1   2021-03-03    t          t 
4   1   2021-04-04                     t
5   1   2021-05-05    t     t
6   1   2021-06-06               t

报告必须是这样的:

TASK     MOST RECENT
sweep    2021-05-05
dust     2021-05-05
vacuum   2021-06-06
wash     2021-04-04

我想找出最有效的查询方法,以便我可以在数据表中显示日期,因为我将跟踪的数据库中可能有多达 100,000 个项目。

注意:如果需要,我可以更改日期/任务数据的存储方式以提高报告效率。

标签: sqlpostgresqlperformancesubquery

解决方案


你可以做:

(
  select 'sweep' as task, date from t 
  where sweep = 't' order by date desc limit 1
) union all (
  select 'dust', date from t 
  where dust = 't' order by date desc limit 1
) union all (
  select 'vacuum', date from t 
  where vacuum = 't' order by date desc limit 1
) union all (
  select 'wash', date from t 
  where wash = 't' order by date desc limit 1
)

为了确保此查询的超快性能,您需要创建以下索引:

create index ix1 on t (sweep, date);
create index ix2 on t (dust, date);
create index ix3 on t (vacuum, date);
create index ix4 on t (wash, date);

推荐阅读