mysql - 可以优化时间属性查询以删除 MAX 子查询吗?
问题描述
我有以下 DDL 正在尝试实现时间属性模式
CREATE TABLE IF NOT EXISTS `docs` (
`id` int(6) NOT NULL,
`effective_on` DATE NOT NULL,
`name` varchar(200) NOT NULL,
`value` varchar(200) NOT NULL,
`superceded_by` int(6),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create unique index zzz on `docs` (id);
alter table `docs` add FOREIGN KEY (superceded_by) REFERENCES docs(id) ON DELETE CASCADE;
CREATE UNIQUE INDEX xyz ON `docs` (name, effective_on, superceded_by);
和相应的查询
select `value` from docs
where
superceded_by is null and name = 'p1' and
effective_on = (
select max(effective_on) from docs
where
superceded_by is null
and effective_on <= '2017-01-01'
and name = 'p1' )
http://sqlfiddle.com/#!9/a07c84/1
当前的 SQL 使用子查询,我想知道是否可以将其消除或进一步简化查询以提高性能。
解决方案
为了性能,您应该在
table docs columns (effective_on, name, superceded_by )
你 id 上的唯一索引是不合适的 你已经有一个 id 上的主键索引
而且表本身对外键的约束也没有意义
推荐阅读
- reactjs - What does extension "jsx" do exactly?
- javascript - 在 Angular 6 中声明扩展方法
- javascript - Is there a more efficient way to set a p5.graphics pixel array equal to another using p5.js in javascript?
- sql - SQL Performance Issues running Query with CTE and CrossJoin
- upgrade - request options is missing in angular 6
- javascript - Distance Matrix with dynamic origin or destination
- c# - C# 允许接口属性重载的原因是什么?
- java - 将微服务部署到 Cloud Foundry
- r - 来自 apa_list(list) 的格式化表
- html - 右上角带有图标的文本