100万条数据查询需高手优化下

bing475879749 2011-07-07 11:54:02

select id,class_name,name,sex,age,cn=
(
select top 1 class_name
from release
where rosterid=roster.id
order by [years] desc,month desc
),
f_time=
(
select top 1 f_time
from release
where rosterid=roster.id
order by [years] desc,month desc
)
from roster
where userid=1012


cn,f_time两个查询是一样的,怎么能够优化下,100万条数据要查询半天
...全文
130 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
--小F-- 2011-07-07
  • 打赏
  • 举报
回复
select
a.id,a.class_name,a.name,a.sex,a.age,max(b.class_name), max(f_time)
from
roster a,release b
where
a.id=a.rosterid
group by
a.id,a.class_name,a.name,a.sex,a.age
rucypli 2011-07-07
  • 打赏
  • 举报
回复
userid,id上加联合索引

rosterid加索引
-晴天 2011-07-07
  • 打赏
  • 举报
回复
在 select 子句中采用子查询是最需要避免的,其实你完全可以用连接来代替!
varbinary 2011-07-07
  • 打赏
  • 举报
回复
2005+

select id,class_name,name,sex,age
,cn=c.class_name
,f_time=c.f_time
from roster a
outer apply (
select top 1 class_name ,f_time
from release b
where b.rosterid=a.id
order by b.[years] desc,b.month desc
) as c
where a.userid=1012

注意是否用到索引
赛里木 2011-07-07
  • 打赏
  • 举报
回复
LEFT JOIN 也是不错的选择
mingxingxia 2011-07-07
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 varbinary 的回复:]
2005+


SQL code
select id,class_name,name,sex,age
,cn=c.class_name
,f_time=c.f_time
from roster a
outer apply (
select top 1 class_name ,f_time
from release b
where b.rosterid=a.id
ord……
[/Quote]
这个可以的
xuzhuhp 2011-07-07
  • 打赏
  • 举报
回复
采用索引,最好尽量不要采用子查询,因为会更慢
bing475879749 2011-07-07
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 qianjin036a 的回复:]
在 select 子句中采用子查询是最需要避免的,其实你完全可以用连接来代替!
[/Quote]

怎么查?
bing475879749 2011-07-07
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 fredrickhu 的回复:]
SQL code

select
a.id,a.class_name,a.name,a.sex,a.age,max(b.class_name), max(f_time)
from
roster a,release b
where
a.id=a.rosterid
group by
a.id,a.class_name,a.name,a.sex,a.age
[/Quote]

查询出来的max值都是一样的
小笨熊 2011-07-07
  • 打赏
  • 举报
回复
不要用嵌套查询,影响性能,最好用连接,鉴于你的数据比较多,还是建索引吧。
qgqch2008 2011-07-07
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 qianjin036a 的回复:]

在 select 子句中采用子查询是最需要避免的,其实你完全可以用连接来代替!
[/Quote]同意

22,206

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧