首页 > 解决方案 > 可以优化时间属性查询以删除 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 使用子查询,我想知道是否可以将其消除或进一步简化查询以提高性能。

标签: mysqlsql

解决方案


为了性能,您应该在

table docs  columns (effective_on, name, superceded_by ) 

你 id 上的唯一索引是不合适的 你已经有一个 id 上的主键索引

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


推荐阅读