2014-10-31 31 views
2

我在MySQL中有一個表,有7 500 000行,我有查詢持續時間的問題。任何人都可以幫助我一些提示,使其更快? 表被稱爲「出席」。它有col移動日期,employee_id索引,我試圖在兩個col上創建一個索引。然而,下面的查詢需要大約9秒,對我來說太慢了。有沒有人有一些提示?我需要使用超過14名員工ID進行選擇。MySQL優化 - 7.5m行

SELECT * 
FROM attendance 
WHERE movement_date >= '2014-09-01 00:00:00' 
AND movement_date <= '2014-10-01 23:59:59' 
AND employee_id IN (14 integer ids...); 

表定義:

CREATE TABLE `attendance` (
    `attendance_id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `attendance_raw_id` int(10) unsigned DEFAULT NULL, 
    `employee_id` int(11) NOT NULL, 
    `shift_type_id` int(11) DEFAULT NULL, 
    `shift_plan_id` int(11) DEFAULT NULL, 
    `record_status_id` tinyint(4) DEFAULT ''1'', 
    `movement_date` datetime DEFAULT NULL, 
    `attendance_movement_type_id` tinyint(4) DEFAULT NULL, 
    `note` varchar(50) DEFAULT NULL, 
    `created_d` datetime DEFAULT NULL, 
    `created_w` int(11) DEFAULT NULL, 
    `updated_w` int(11) DEFAULT NULL, 
    PRIMARY KEY (`attendance_id`), 
    UNIQUE KEY `IDX_attendance_raw_id` (`attendance_raw_id`), 
    KEY `IDX_employee_id` (`employee_id`), 
    KEY `FK_attendance3` (`attendance_movement_type_id`), 
    KEY `IDX_movement_date` (`movement_date`), 
    KEY `FK_attendance4` (`record_status_id`), 
    KEY `FK_movement_date_employee` (`movement_date`,`employee_id`), 
    CONSTRAINT `FK_attendance` FOREIGN KEY (`employee_id`) REFERENCES `employee` (`employee_id`), 
    CONSTRAINT `FK_attendance2` FOREIGN KEY (`attendance_raw_id`) REFERENCES `attendance_raw` (`attendance_raw_id`), 
    CONSTRAINT `FK_attendance3` FOREIGN KEY (`attendance_movement_type_id`) REFERENCES `attendance_movement_type` (`attendance_movement_type_id`), 
    CONSTRAINT `FK_attendance4` FOREIGN KEY (`record_status_id`) REFERENCES `record_status` (`record_status_id`) 
) ENGINE=InnoDB AUTO_INCREMENT=9072724 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC 
+0

使用'explain'來查看你需要索引的地方。 – Jens 2014-10-31 07:32:50

+0

將表定義添加到問題'show create table attendance'中會給出完整的定義。 – 2014-10-31 07:50:49

+0

我已經添加了這個 – vilda72 2014-10-31 08:02:00

回答

1

爲了提高結果的,你需要改變你的SQL語句,這樣

SELECT * 
FROM attendance 
WHERE movement_date >= '2014-09-01 00:00:00' 
AND movement_date <= '2014-10-01 23:59:59' 
AND employee_id IN(
        SELECT indexed_column_IDs 
        FROM table2 ... 
        ) 

從一定數量的記載,在起動速度對SELECT的謂詞變得比對常量列表的速度快。