有一个员工属性表,有上百万的数据,需要查询出每个员工特定时间最新的数据并过滤,sql执行太慢,
select * from employe_info where id in ( select max(id) from employe group by employe_id where date < '2016-01-01') e
where level = 1 limit 10

解决方案 »

  1.   

    select
    a.列名
    from employe_info a
    left join (
    select max(id) id from employe group by employe_id where date < '2016-01-01'
    )e on a.id=b.id
    where level=1 
    你试试这个写法看看。
      

  2.   

    是一样的慢哈,我想始终group by的结果比较多感觉是否结构上设计就有问题了
      

  3.   

    以文本方式贴出  不要贴截图
    explain select ...
    show index from ..
    以供分析。
      

  4.   

    一方面是索引
    另一方面,你的外层有限制条件 where level = 1 ,这个如果能够大量过滤数据的话,应该考虑在 group by 前也加上这个条件
      

  5.   

    1 PRIMARY employe_info range info_key info_key  10 15110 Using index condition; Using where; Using MRR
    2 SUBQUERY employe_info2 index id_key id_key 10 1608626 Using where
      

  6.   

    我的结构是:
    CREATE TABLE `employe` (
      `id` int(10) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) DEFAULT NULL,
      `address` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    CREATE TABLE `employe_info` (
      `id` int(10) NOT NULL AUTO_INCREMENT,
      `employe_id` int(10) DEFAULT NULL,
      `level` int(2) DEFAULT NULL,
      `date` date DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `fk_employe` (`employe_id`),
      KEY `date_index` (`date`) USING BTREE,
      CONSTRAINT `fk_employe` FOREIGN KEY (`employe_id`) REFERENCES `employe` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
      

  7.   

    show index from ..贴哪去了?
      

  8.   

    show index from ..贴哪去了?可以加一点测试数据:
    INSERT INTO employe (name, address) VALUES ('joe', 'joe address');INSERT INTO employe (name, address) VALUES ('mads', 'mads address');INSERT INTO employe (name, address) VALUES ('max', 'max address');INSERT INTO employe_info (employe_id, level, date) VALUES ('1', '1', '2016-01-01');INSERT INTO employe_info (employe_id, level, date) VALUES ('2', '1', '2016-01-02');INSERT INTO employe_info (employe_id, level, date) VALUES ('3', '1', '2016-01-03');INSERT INTO employe_info (employe_id, level, date) VALUES ('1', '2', '2015-01-01');INSERT INTO employe_info (employe_id, level, date) VALUES ('2', '3', '2015-10-02');INSERT INTO employe_info (employe_id, level, date) VALUES ('3', '4', '2015-08-03');INSERT INTO employe_info (employe_id, level, date) VALUES ('1', '6', '2015-06-01');INSERT INTO employe_info (employe_id, level, date) VALUES ('2', '2', '2015-09-02');INSERT INTO employe_info (employe_id, level, date) VALUES ('3', '4', '2015-06-03');INSERT INTO employe_info (employe_id, level, date) VALUES ('1', '1', '2015-07-01');INSERT INTO employe_info (employe_id, level, date) VALUES ('2', '1', '2015-10-02');INSERT INTO employe_info (employe_id, level, date) VALUES ('3', '1', '2015-11-03');查询语句:select * from employe_info where id in ( select max(id) from employe_info where date < '2016-02-01' group by employe_id ) and level = 1 limit 10