Skip to content

Instantly share code, notes, and snippets.

@kejyun
Created December 20, 2012 09:49
Show Gist options
  • Save kejyun/4344238 to your computer and use it in GitHub Desktop.
Save kejyun/4344238 to your computer and use it in GitHub Desktop.
在MySQL使用Explain做SQL SELECT語法效能測試
-- 建立資料表
-- 留言
CREATE TABLE IF NOT EXISTS `comment` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '編號',
`content` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT '留言',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
-- 使用者
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '編號',
`name` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT '姓名',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;
-- 使用者的留言
CREATE TABLE IF NOT EXISTS `user_comment` (
`user_id` int(10) unsigned NOT NULL COMMENT '使用者編號',
`comment_id` int(10) unsigned NOT NULL COMMENT '評論編號',
PRIMARY KEY (`user_id`,`comment_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- 新增資料
-- 留言
INSERT INTO `comment` (`id`, `content`) VALUES
(1, '留言1'),
(2, '留言2');
-- 使用者
INSERT INTO `user` (`id`, `name`) VALUES
(1, '使用者1'),
(2, '使用者2');
-- 使用者的留言
INSERT INTO `user_comment` (`user_id`, `comment_id`) VALUES
(1, 1),
(1, 2);
-- 解釋MySQL語法效能
-- 撈取留言資料
EXPLAIN SELECT * FROM `comment` WHERE id` =2;
-- 撈取使用者的留言資料
EXPLAIN SELECT *
FROM `comment` c, `user` u, `user_comment` uc
WHERE u.`id` = uc.`user_id`
AND uc.`comment_id` = c.`id`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment