希望对使用索引(或者实际上是查询本身)优化 MySQL 查询有所帮助。
表结构:
CREATE TABLE IF NOT EXISTS `match_current` (
`partnership_id` int(11) NOT NULL AUTO_INCREMENT,
`runs` int(5) NOT NULL DEFAULT '0',
`balls` int(5) NOT NULL DEFAULT '0',
`user1_id` bigint(11) NOT NULL,
`user1_firstname` char(20) NOT NULL,
`user1_lastname` char(20) NOT NULL,
`user1_runs` int(5) NOT NULL DEFAULT '0',
`user1_balls` int(5) NOT NULL DEFAULT '0',
`user1_strike` tinyint(1) NOT NULL DEFAULT '1',
`user1_out` tinyint(1) NOT NULL DEFAULT '0',
`user1_retired` tinyint(1) NOT NULL DEFAULT '0',
`user2_id` bigint(11) NOT NULL,
`user2_firstname` char(20) NOT NULL,
`user2_lastname` char(20) NOT NULL,
`user2_runs` int(5) NOT NULL DEFAULT '0',
`user2_balls` int(5) NOT NULL DEFAULT '0',
`user2_strike` tinyint(1) NOT NULL DEFAULT '0',
`user2_out` tinyint(1) NOT NULL DEFAULT '0',
`user2_retired` tinyint(1) NOT NULL DEFAULT '0',
`last_over` char(15) NOT NULL,
`ball_by_ball` varchar(1000) NOT NULL,
`facebook` tinyint(1) NOT NULL DEFAULT '0',
`friends` tinyint(1) NOT NULL DEFAULT '0',
`nudge` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`started` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`status` tinyint(1) NOT NULL DEFAULT '1',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`partnership_id`),
UNIQUE KEY `user1_id_2` (`user1_id`,`user2_id`,`facebook`),
KEY `user2_id` (`user2_id`),
KEY `user1_id` (`user1_id`),
KEY `facebook` (`facebook`),
KEY `status` (`status`),
KEY `friends` (`friends`),
KEY `timestamp` (`timestamp`),
KEY `user1_id_3` (`user1_id`,`user1_strike`),
KEY `user2_id_2` (`user2_id`,`user2_strike`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=36139 ;
示例查询:
SELECT *
FROM match
WHERE status = 1
AND (
(user1_id=1234 AND user1_strike=1) OR
(user2_id=4321 AND user2_strike=1)
)
ORDER BY timestamp ASC
查询显然有效,而且做得还不错,但我们最近确实增加了流量,现在我可以看到它开始挣扎了。
干杯!