查询很慢,要索引哪些字段

时间:2013-02-16 01:34:00

标签: mysql query-optimization innodb

我有这个问题:

select * from 

当我执行它时,需要约45秒,记录为35k。每天我都会向gps_unit_location表添加5k +新记录。所以桌子会增长。 我所有id的当前索引。是否会添加任何其他索引可以帮助我提高此查询的性能?

感谢。

2 个答案:

答案 0 :(得分:2)

所以,

  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
    
  4. 另外,我认为您不需要在定义为主键的列上使用唯一索引,这会导致插入/更新语句的写入开销。

答案 1 :(得分:1)

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

哦,让你的所有身份证都'无符号'。