请教一个SQL语句查询效率的问题在线等

zxecp 2011-09-03 10:18:30
现在 由一张投票日志表
lod_id 日志ID
vote_id 投票主题ID
user_id 投票用户ID
vote_time 投票时间
vote_ip 投票IP


现在有三个限制条件:
条件一:一个用户投票间隔时间必须大于1个小时
条件二:一个用户一天只能投票三次
条件三:一个IP一天只能投票九次


我想问下,我应该怎么处理三个条件的顺序 才能更合理,就是如果一个条件不满足就直接返回

我理解是应该查询耗资源是有易到难,这三个应该谁先谁后?
谢谢
...全文
77 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
木小舟 2011-09-05
  • 打赏
  • 举报
回复
and 好点
xyc880813 2011-09-05
  • 打赏
  • 举报
回复
哎。。。在索引上面SQL可进步的地方就是这个
允许索引中加入条件表达式

想一下 如果索引就是按照你这个逻辑条件表达式建立的
那么查询是不是更快了?

期待SQL 2012。。。
xyc880813 2011-09-05
  • 打赏
  • 举报
回复
当你用And操作符连接这3个条件之后
SQL的查询分析器会根据表中的统计信息(自动生成的)自动来处理优先级的问题
SQL的查询分析器会从根据统计信息,找到开销最小的条件,开始进行表扫描
这里先不考虑列上有索引的情况,只是当表是个heap
SQL的查询分析器会根据统计信息,找到根据统计信息中,数据量最小的条件开始找
比如表有1万5千行
vote_ip 投票IP列有1万个不同的数据,user_id 投票用户ID有3000个不同的数据的话
那么基本上SQL查询分析器就会有限考虑扫描列user_id上面的条件
当然这都是举例
实际情况要根据你表中数据量的唯一性(也就是列的“可选择性”)的大小来自动决定条件的
楼主的想法很好 但是这个地方SQL是自己来处理的 动态生成查询计划
当然也有办法强制SQL分析器执行你想要的计划
但是一般来说 这个工作交给查询分析器就好

在这些条件列上建立不同的索引会有很好的效果
rucypli 2011-09-03
  • 打赏
  • 举报
回复
会自动优化的
-晴天 2011-09-03
  • 打赏
  • 举报
回复
哇,后一个group 错了!
select * from tb a
where not exists(select 1 from tb where [user_id]=a.[user_id] and abs(datediff(mi,a.vote_time,vota_time))<=60)
and not exists(select 1 from tb where [user_id]=a.[user_id] and convert(varchar(10),vote_time,120)=convert(varchar(10),a.vote_time,120) group by [user_id] having count(*)>3)
and not exists(select 1 from tb where vote_ip=a.vote_ip and convert(varchar(10),vote_time,120)=convert(varchar(10),a.vote_time,120) group by [vote_ip] having count(*)>9)


-晴天 2011-09-03
  • 打赏
  • 举报
回复
应该用and
select * from tb a
where not exists(select 1 from tb where [user_id]=a.[user_id] and abs(datediff(mi,a.vote_time,vota_time))<=60)
and not exists(select 1 from tb where [user_id]=a.[user_id] and convert(varchar(10),vote_time,120)=convert(varchar(10),a.vote_time,120) group by [user_id] having count(*)>3)
and not exists(select 1 from tb where vote_ip=a.vote_ip and convert(varchar(10),vote_time,120)=convert(varchar(10),a.vote_time,120) group by [user_id] having count(*)>9)


-晴天 2011-09-03
  • 打赏
  • 举报
回复
select * from tb a
where not exists(select 1 from tb where [user_id]=a.[user_id] and abs(datediff(mi,a.vote_time,vota_time))<=60)
or not exists(select 1 from tb where [user_id]=a.[user_id] and convert(varchar(10),vote_time,120)=convert(varchar(10),a.vote_time,120) group by [user_id] having count(*)>3)
or not exists(select 1 from tb where vote_ip=a.vote_ip and convert(varchar(10),vote_time,120)=convert(varchar(10),a.vote_time,120) group by [user_id] having count(*)>9)
--小F-- 2011-09-03
  • 打赏
  • 举报
回复
查询优化器会自动优化的

如果连接条件是AND 应该效率差不多

zxecp 2011-09-03
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 qianjin036a 的回复:]
检索方法一样的话,消耗资源也应该差不多.
[/Quote]

我知道我这样 有些吹毛求疵,但是 程序里面 好就是好,哪怕就好一点点 也是不一样的 不是吗
-晴天 2011-09-03
  • 打赏
  • 举报
回复
检索方法一样的话,消耗资源也应该差不多.

27,581

社区成员

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

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