| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 8207 人关注过本帖
标题:300万条数据,3张表联合查询 select top 8 要8秒多,怎么提高查询效率?
只看楼主 加入收藏
sw4433
Rank: 1
等 级:新手上路
帖 子:65
专家分:0
注 册:2009-5-24
收藏
得分:0 
我想查询评论最多 的newsid
select  top 8 com.newsId , count(id) as countId  from comment com
    where not exists(select 1 from comment where newsId = com.newsId and id>com.id)
    group by com.newsId
    order by countId desc
查询结果好像不对

查询评论最多的前几条数据的 newsid,
比如说
newsid :
99451
39
39
46
39
46
99451
99451
99451
99490
1000000
99451
47
47
47
47
47
47
我要的结果:  按评论最多到最少排序
47 (6条评论)
99451 (5条评论)
39 (3条评论)
46 (2条评论)

sql语句应该怎么写?
2010-09-20 09:16
cnfarer
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:179
帖 子:3330
专家分:21157
注 册:2010-1-19
收藏
得分:0 
试试吧,不知可否?
select n.id,n.title,n.createTime,c.[name],c.id as  caID, from (select top 8 newsid,count(id) as comcount from comment group by newid order by comcount desc) cnt inner join news n on cont.newsid=n.id inner join category c on n.caid=c.id

如果comment表在newsid上有索引news表在caid上有索引!我想对查询效率是会有较大提升的。

★★★★★为人民服务★★★★★
2010-09-20 20:07
cnfarer
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:179
帖 子:3330
专家分:21157
注 册:2010-1-19
收藏
得分:0 
上述语句中当然也可以用left outer join,测试一下,做个对比。希望将结果公示!

★★★★★为人民服务★★★★★
2010-09-20 20:12
sw4433
Rank: 1
等 级:新手上路
帖 子:65
专家分:0
注 册:2009-5-24
收藏
得分:0 
搞定了!
下面是原来的sql语句:
news(新闻表),category(分类表),comment(评论表) 都与news表有主外键关系
这是原来的sql语句   (查询时间8秒左右,而且 CUP 占用率很高!)
select top 8 n.id,n.title,n.createTime,c.[name],count(com.id) as comCount,
    c.id as caId
    from news n
    left join category c on n.caId = c.id
    left join comment com on com.newsId = n.id
    group by n.id,n.title,n.createTime,c.[name],c.id
    order by comCount desc

这是根据 版主 cnfarer 的建议改进过的sql语句   (查询时1秒不到,接近0秒)
查询前8条评论最多的新闻
select n.id,n.title,n.createTime,c.[name],c.id as caId
    from news n
    left join category c on n.caId = c.id
    where n.id in
    (
        select top 8  newsId from comment com
         group by com.newsId
        order by count(newsid) desc
    )
感谢
版主 cnfarer  !!
2010-09-23 10:43
快速回复:300万条数据,3张表联合查询 select top 8 要8秒多,怎么提高查询效率 ...
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015757 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved