[英]How can I make this mysql query more efficient?
我有一个类别表,帖子和一个M2M表category_post。 这是他们的图式
CREATE TABLE IF NOT EXISTS `posts` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`title` char(255) COLLATE utf8_unicode_ci NOT NULL,
`img_url` char(255) CHARACTER SET latin1 NOT NULL,
`content` text COLLATE utf8_unicode_ci NOT NULL,
`pub_date` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `pub_date` (`pub_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=42166 ;
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `category` (
`c_id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`c_name` char(255) CHARACTER SET latin1 NOT NULL,
`c_slug` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`c_active` tinyint(1) NOT NULL,
PRIMARY KEY (`c_id`),
KEY `c_slug` (`c_slug`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='List of Categories' AUTO_INCREMENT=47 ;
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `category_post` (
`cp_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`category_id` tinyint(3) unsigned NOT NULL,
`post_id` mediumint(8) unsigned NOT NULL,
PRIMARY KEY (`cp_id`),
KEY `category_id` (`category_id`),
KEY `post_id` (`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=60909 ;
这是一个示例查询。 通常需要大约0.60秒,在负载下高达3秒。
SELECT *
FROM posts p
INNER JOIN category_post cp ON p.id = cp.post_id
WHERE cp.category_id IN ( 10, 11, 12, 13, 15, 19, 33, 37, 46 )
GROUP BY id
ORDER BY pub_date DESC
LIMIT 25690 , 10
说明:
我已经阅读了许多参考资料和SO帖子,并对如何使用它有些困惑。 我希望在正确的方向上点头!
我发现如果不包含“ ORDER BY pub_date DESC”,查询将在短时间内执行。 但是pub_date是一个索引。 我在某处读到mysql每个查询只会使用一个索引。 那就是为什么它慢吗?
我看到在决策上下文( where
, join
)中使用的任何字段都有索引。
我认为您应该将SELECT *
替换为SELECT to-be-used-column
。
因为过多的列会减慢速度。 但是,这不是基本问题。
希望它能希望你。
解决方案是执行后行查找。 更多信息在这里 。 将执行时间从600ms减少到仅90ms
这是更新的查询:
SELECT p.*
FROM (
SELECT id
FROM posts temp
INNER JOIN category_post cp ON temp.id = cp.post_id
WHERE cp.category_id IN ( 10, 11, 12, 13, 15, 19, 33, 37, 46 )
GROUP BY id
ORDER BY pub_date ASC
LIMIT 25690 , 10
) id_array
JOIN posts p ON p.id = id_array.id
ORDER BY p.pub_date ASC
谢谢大家的建议:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.