mysql limit 索引失效,使用MySQL“LIMIT 1”是否有任何意义?查询索引/唯一字段时?...

For example, I'm querying on a field I know will be unique and is indexed such as a primary key. Hence I know this query will only return 1 row (even without the LIMIT 1)

SELECT * FROM tablename WHERE tablename.id=123 LIMIT 1

or only update 1 row

UPDATE tablename SET somefield='somevalue' WHERE tablename.id=123 LIMIT 1

Would adding the LIMIT 1 improve query execution time if the field is indexed?

解决方案

Is there any point using MySQL “LIMIT 1” when querying on primary key/unique field?

It is not good practice to use LIMIT 1 when querying with filter criteria that is against either a primary key or unique constraint. A primary key, or unique constraint, means there is only one row/record in the table with that value, only one row/record will ever be returned. It's contradictory to have LIMIT 1 on a primary key/unique field--someone maintaining the code later could mistake the importance & second guess your code.

But the ultimate indicator is the explain plan:

explain SELECT t.name FROM USERS t WHERE t.userid = 4

...returns:

id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra

-----------------------------------------------------------------------------------------------------

1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 |

...and:

explain SELECT t.name FROM USERS t WHERE t.userid = 4 LIMIT 1

...returns:

id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra

-----------------------------------------------------------------------------------------------------

1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 |

Conclusion

No difference, no need. It appears to be optimized out in this case (only searching against the primary key).

What about an indexed field?

An indexed field doesn't guarantee uniqueness of the value being filtered, there could be more than one occurrence. So LIMIT 1 would make sense, assuming you want to return one row.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值