查询速度慢,哪些字段建立索引

问题描述:

我有这个疑问:查询速度慢,哪些字段建立索引

select * from 

当我执行它,它需要〜45秒用35K的记录。每天我都会向gps_unit_location表添加5k +个新记录。所以表会增长。 我所有的id都是当前的索引。将添加任何额外的索引将帮助我改进此查询的性能?

谢谢。

+0

请至少用'EXPLAIN'更新你的问题。最好是一个'SHOW CREATE TABLE'。 – Kermit 2013-02-16 01:36:50

+0

@njk,我添加了创建表 – Andrew 2013-02-16 01:45:43

+0

@Sebas,查询在顶部 – Andrew 2013-02-16 01:47:03

所以,

  1. 确保您有NOT NULL列和指标:

    INDEX ON gps_unit_location.idgps_unit_location 
    INDEX ON user.iduser 
    INDEX ON user_to_gps_unit.iduser 
    INDEX ON user_to_gps_unit.idgps_unit 
    INDEX ON gps_unit.idgps_unit 
    INDEX ON gps_unit_location.idgps_unit 
    
  2. 确定自己真的需要选择所有与明星*

  3. 领域尝试这个查询:

    SELECT 
        `gps_unit`.`idgps_unit`, 
        `gps_unit`.`name as name`, 
        `gps_unit`.`notes as notes`, 
        `gps_unit`.`serial`, 
        `gps_unit_location`.`dt` as dt, 
        `gps_unit_location`.`idgps_unit_location`, 
        `gps_unit_location`.`lat`, 
        `gps_unit_location`.`long`, 
        `ip`, 
        `unique_id`, 
        `loc_age`, 
        `reason_code`, 
        `speed_kmh`, 
        `VehHdg`, 
        `Odometer`, 
        `event_time_gmt_unix`, 
        `switches`, 
        `engine_on_off` 
    FROM user 
    INNER JOIN user_to_gps_unit ON user.iduser = user_to_gps_unit.iduser 
    INNER JOIN gps_unit   ON user_to_gps_unit.idgps_unit = gps_unit.idgps_unit 
    INNER JOIN gps_unit_location ON gps_unit.idgps_unit = gps_unit_location.idgps_unit 
    INNER JOIN 
         (SELECT 
          `gps_unit_location`.`idgps_unit`, 
          MAX(`gps_unit_location`.`dt`) dtmax 
         FROM `gps_unit_location` 
         GROUP BY 1 
         ) r1 ON r1.idgps_unit = gps_unit_location.idgps_unit AND r1.dtmax = gps_unit_location.dt 
    WHERE 
        user.iduser = 14 
    

在附注上,我认为您不需要定义为主键的列上的唯一索引,这会导致insert/update语句的写入开销。

+1

查询优化。请仔细检查结果。 – Sebas 2013-02-16 03:09:08

+1

我很期待你测试它hehehe :-) – Sebas 2013-02-16 03:21:33

+0

,它的工作原理!您设法将执行时间从45秒缩短到29秒!尽管如此,它仅仅是4万条记录!它如何与1mil记录一起使用? 你对如何改善它有什么想法吗? – Andrew 2013-02-16 17:44:25

通用的答案是索引那些用于连接和约束的列(ON和WHERE子句)。使用复合索引(首先连接,然后使用最低基数约束的约束)。

哦,并使所有的ID'无符号'。