2017-08-09 110 views
0

以下引發慢速查詢日誌。清除MYSQL緩慢查詢日誌 - Rails

APN::Notification. 
    select('apn_notifications.*, devices.device_uid'). 
    joins('INNER JOIN apn_devices ON (apn_notifications.device_id = apn_devices.id) INNER JOIN devices ON (apn_devices.device_id = devices.id)'). 
    where(['apn_notifications.sent_at IS NULL AND apn_notifications.badge > 0 AND devices.customer_id = ? AND devices.device_type IN (?)', customer.id, Object::Device.platform_device_types('ios')]) 

的輸出EXPLAIN

EXPLAIN for: SELECT apn_notifications.*, devices.device_uid FROM `apn_notifications` INNER JOIN apn_devices ON (apn_notifications.device_id = apn_devices.id) INNER JOIN devices ON (apn_devices.device_id = devices.id) WHERE (apn_notifications.disabled_at IS NULL) AND (apn_notifications.sent_at IS NULL AND apn_notifications.badge > 0 AND devices.customer_id = 1 AND devices.device_type IN ('iphone4','ipad','iphone3')) 

'的輸出顯示創建表apn_notifications'

| apn_notifications | CREATE TABLE `apn_notifications` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`device_id` int(11) DEFAULT NULL, 
`errors_nb` int(11) DEFAULT NULL, 
`device_language` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, 
`sound` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, 
`alert` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, 
`badge` int(11) DEFAULT NULL, 
`custom_properties` text COLLATE utf8_unicode_ci, 
`sent_at` datetime DEFAULT NULL, 
`disabled_at` datetime DEFAULT NULL, 
`created_at` datetime DEFAULT NULL, 
`updated_at` datetime DEFAULT NULL, 
PRIMARY KEY (`id`), 
KEY `index_apn_notifications_on_device_id` (`device_id`) 
) ENGINE=InnoDB AUTO_INCREMENT=12984412 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci | 

的apn_notifications表中有150萬條記錄。所以,如果我嘗試添加索引,它需要更長的時間。什麼是從慢查詢中刪除此最佳方法?

另外從Mysql 5.6開始,添加索引不會導致任何停機。我對嗎?

+0

你的問題是什麼? – vijoc

+0

添加我的問題。 –

回答

0

我添加了以下索引,並減少了大量的時間。

add_index :apn_notifications, :sent_at 
add_index :apn_notifications, :badge 

注:已爲外鍵

添加索引
1

往往是 「複合」 指標都比較好:

apn_notifications: INDEX(device_id, sent_at, badge) 
apn_notifications: INDEX(sent_at, badge) 
devices: INDEX(customer_id, device_type) 

apn_devices是許多一對多映射?如果是,請檢查它是否遵循指導here