大数据量的情况下,判断记录有无,select count(id) from , 比select id from要快一点吧

lylhyh 2014-11-06 11:21:44
大数据量的情况下,判断记录有无,select count(id) from , 比select id from要快一点吧
id是主键
...全文
417 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
S117 2014-11-09
  • 打赏
  • 举报
回复
主键有索引的,select id from肯定比select count(id) from快了
  • 打赏
  • 举报
回复
引用 8 楼 ACMAIN_CHM 的回复:
[quote=引用 6 楼 micropentium6 的回复:] [quote=引用 5 楼 ACMAIN_CHM 的回复:] select id from xx lmit 1 要快一些。 select count(id) from , select id from 从语义上本身就不同,一个是返回一条记录,一个是返回表中所有记录。
if there is no index on column id, then in the worst case, all 3 queries could be O(n)?[/quote]O(1), O(n), O(1)[/quote] could you please elaborate? select count(1231) from city;最慢; select id from city where Id=1231;要快一些; select id from city where Id=1231 limit 1;最快。 if there is no index, say id=1231 is the last record, IMHO, does mysql have to loop through all records to get the there? that why I thought the worst time complexity could be n. Why do you think the first and the third queries can be done in O(1)? thx!
ACMAIN_CHM 2014-11-07
  • 打赏
  • 举报
回复
引用 6 楼 micropentium6 的回复:
[quote=引用 5 楼 ACMAIN_CHM 的回复:] select id from xx lmit 1 要快一些。 select count(id) from , select id from 从语义上本身就不同,一个是返回一条记录,一个是返回表中所有记录。
if there is no index on column id, then in the worst case, all 3 queries could be O(n)?[/quote]O(1), O(n), O(1)
  • 打赏
  • 举报
回复
引用 5 楼 ACMAIN_CHM 的回复:
select id from xx lmit 1 要快一些。 select count(id) from , select id from 从语义上本身就不同,一个是返回一条记录,一个是返回表中所有记录。
if there is no index on column id, then in the worst case, all 3 queries could be O(n)?
加油馒头 2014-11-07
  • 打赏
  • 举报
回复
经实际使用发现,判断记录有无用:select id from 快,在数据量大的情况下。
ACMAIN_CHM 2014-11-06
  • 打赏
  • 举报
回复
select id from xx lmit 1 要快一些。 select count(id) from , select id from 从语义上本身就不同,一个是返回一条记录,一个是返回表中所有记录。
zhu19774279 2014-11-06
  • 打赏
  • 举报
回复
17w的数据经测试, select count(1231) from city;最慢; select id from city where Id=1231;要快一些; select id from city where Id=1231 limit 1;最快。
ayzen1988 2014-11-06
  • 打赏
  • 举报
回复
第二句加上limit 1会好很多
pony520 2014-11-06
  • 打赏
  • 举报
回复
select count(id) from tb; select id from tb limit 1; 如果只是用来判断表只有没有记录的话,第二个好,在用FOUND_ROWS()函数就可以了

56,678

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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