sql - 高效查询和保存布尔列的最近日期
问题描述
我有一个保存日期的表格,事情是在日期之后由一个布尔值完成的。我需要对此进行查询以运行报告,该报告告诉我每个最新列的完成日期。所以表格看起来像这样:
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 个项目。
注意:如果需要,我可以更改日期/任务数据的存储方式以提高报告效率。
解决方案
你可以做:
(
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);
推荐阅读
- java - ReadableMap 中的键数?
- function - 有没有办法通过函数传递/选择输出?
- java - 用 JSON 从字符串中解析数组?
- php - 如何使用 php pdo 从 mysql 中的存储过程/函数获取返回值
- java - 如何使用 substring 方法返回奇数字符串的中间 3 个字符?
- html - 如何在不破坏 CSS 滑块开关的情况下对齐它们
- php - 从 URL 自动填充下拉列表
- react-native - 找出 React Native 项目中未使用的导入
- javascript - 如何使用 Strapi 创建自定义注册和登录 API?
- php - 如何预测不断变化的多维数组并将所有数据关联到适当的位置