Mysql 可以优化时态属性查询以删除MAX子查询吗?

Mysql 可以优化时态属性查询以删除MAX子查询吗?,mysql,sql,Mysql,Sql,我有下面的DDL,它正试图实现 以及相应的查询 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' ) 当前SQL使用了一个子查询,我想知道

我有下面的DDL,它正试图实现

以及相应的查询

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' )

当前SQL使用了一个子查询,我想知道是否可以消除该子查询或进一步简化查询以提高性能。

为了提高性能,您应该在其上添加一个复合索引

table docs  columns (effective_on, name, superceded_by ) 
如果id上已有主键索引,则id上的唯一索引将取消


而且表上的外键约束本身对性能没有意义,您应该在其上添加一个复合索引

table docs  columns (effective_on, name, superceded_by ) 
如果id上已有主键索引,则id上的唯一索引将取消


而且表上的外键约束本身没有意义

我将这样编写查询:

select d.`value`
from docs d
where d.superceded_by is null and
      d.name = 'p1' and
      d.effective_on = (select max(d2.effective_on)
                        from docs d2
                        where d2.superceded_by is null and
                              d2.name = d.name and
                              d2.effective_on <= '2017-01-01'
                       );

然后你需要一个docsname上的索引,替换为,生效。索引中列的顺序非常重要。第一个键用于correlation子句;第二个用于通过替换_进行过滤。然后,应扫描最后一个键以获得正确的日期。

我将这样编写查询:

select d.`value`
from docs d
where d.superceded_by is null and
      d.name = 'p1' and
      d.effective_on = (select max(d2.effective_on)
                        from docs d2
                        where d2.superceded_by is null and
                              d2.name = d.name and
                              d2.effective_on <= '2017-01-01'
                       );
然后你需要一个docsname上的索引,替换为,生效。索引中列的顺序非常重要。第一个键用于correlation子句;第二个用于通过替换_进行过滤。然后,应扫描最后一个密钥以获得正确的日期