我们致力于一个MySQL知识的分享网站

  |   本站Feed      

查询优化:说说一个数据库的查询方法

2009-06-02 23:29:20  |   才被阅读:2,915 次  |   才2条评论
分类: MySQL优化设计  |   发布: OurMySQL  |   来源:新浪开发者博客
标签:

最近做了博客关注系统的方案设计,主要的数据表有两个:
数据内容表:

CREATE TABLE `story` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uid` int(10) unsigned NOT NULL,
`type` tinyint(3) unsigned NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`data` varbinary(8192) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `i_ut` (`uid`,`type`,`time`)
) ENGINE=InnoDB;

以及关注关系表:

CREATE TABLE `attention` (
`uid` int(10) unsigned NOT NULL,
`aid` int(10) unsigned NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`uid`,`aid`),
KEY `i_a` (`aid`)
) ENGINE=InnoDB;

我们的要查询出uid为1001的用户A关注的所有人最近发表的内容,结果集大概在10000条,我们只取前20条。
简单直接的查询方法可以是:

select id,data from story,attention
where story.uid=attention.aid and attention.uid=1001 order by time desc,id desc limit 20;

但是这个查询语句效率很低,换用一种貌似比较复杂的查询:

select story.* from
story,
(select id from story,attention
where story.uid=attention.aid and attention.uid=1001 order by time desc,id desc
) relation
where story.id=relation.id limit 20;

这个查询效率就很好了,通过对比发现,至少比上一个查询快几十倍。

我认为这样的差异主要取决于数据库中“”的实现,可能MySQL在这方面做的有限,需要我们精确的告诉他一个比较优化的查询方案。

相关文章

  • 目前没有相关的文章

2 Responses to “查询优化:说说一个数据库的查询方法”

  1. longines Says:

    一直没注意过,没想到速度相差如此之大


  2. tz Says:

    第一条sql 如果不修改 根本不能执行……


Leave a Reply