SQL left join 查询

zhangzhenshuang 2013-03-08 06:48:42
with tb1 as
(select count(uid) as totalregister,ggsiteid
from UserSystem where ggsiteid
in(select code from PromotionCode where scode=102013)
and ( regdate between '2013-03-05' and '2013-03-08') group by ggsiteid )
, tb2 as
(select sum(a.paymoney) as totalmoney,count(distinct(a.uid)) as totalpay,
b.ggsiteid
from user_czhistory as a
left join
(select regdate,uid,ggsiteid from usersystem
where ggsiteid in(select code from PromotionCode where scode=102013)
and regdate>='2013-03-05' and regdate<'2013-03-08'
)
as b
on a.uid=b.uid
where a.updatetime<=dateadd(dd,1,b.regdate)
group by b.ggsiteid)

select * from tb1 left join tb2
on tb1.ggsiteid=tb2.ggsiteid

表tb1数据:
1516 1116
1459 1117
3457 1118
890 1119
1031 1122

如果表tb2数据为:
30 1 1117
查询超慢,不出来
如果数据为:
290 5 1117
610 3 1118
1000 2 1119
10 1 1122
则可以查询出来
这是什么原因
...全文
187 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
csdnTimePeriod 2013-03-13
  • 打赏
  • 举报
回复
Between and就有些慢。同意楼上的建议,对执行性能有影响的部分改写试试。
zhangzhenshuang 2013-03-10
  • 打赏
  • 举报
回复
如果不用with,至今拼接sql语句也是只有在regdate>='2013-03-05'这个条件时读取超慢,其他日期条件很快。 我查了下,当日期是2013-03-05的时候,表tb2只有一条数据,不知道跟这有关系没。我如果用临时表,速度稍慢一点,但是也能查出来
發糞塗牆 2013-03-08
  • 打赏
  • 举报
回复
1、left join的确比inner join会慢,但是有时候必须用外联结。 2、用CTE的话,主要是迭代运算,如果你的逻辑不合理,那么按理应该会在大概默认是100行的时候停止并报错。不会一直运算吧。 3、CTE对于大数据量,即使逻辑正确,也是很慢的。 4、看看执行计划,百分比主要落在什么操作上。
shoppo0505 2013-03-08
  • 打赏
  • 举报
回复
tb1和tb2的关连没有什么问题,运算慢不是这里的问题。 你的tb1,tb2的结果计算每次都是很快就能出来么?应该是with语句中的问题。

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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