使用已知最大计数的限制语句是否更快?

Is it faster to use limit statement with known max count?

来自大型 table 的查询,例如:

select something from sometable limit somecount;

我知道 limit 语句对于避免从查询中获取太多行很有用。 但是当没有多少行但在一个大 table 中时使用它怎么样? 例如,有一个 table create like this

CREATE TABLE if not exists users (
    id integer primary key autoincrement,
    name varchar(80) unique not null,
    password varchar(20) not null,
    role integer default 1,  -- 0 -> supper admin; 1 -> user
    banned integer default 0 
);

案例 1:我想获取 id=100 的用户。这里id是主键, 它肯定可以在 most.which 处获得 1 行在下面的 2 个语句之间更快吗?

select * from users where id=100;
select * from users where id=100 limit 1;

案例 2:我想获取 name='jhon' 的用户。这里的名字是独一无二的, 它还可以在 most.which 处获得 1 行在下面的 2 个语句之间更快?

select * from users where name='jhon';
select * from users where name='jhon' limit 1;

案例 3:我想获取角色=0 的用户。这里的角色既不是主键 也不是唯一的,但我知道最多只有 10 行。下面两个语句哪个更快?

select * from users where role=0;
select * from users where role=0 limit 10;

如果您关心性能,则添加索引来处理所有三个查询。这需要一个额外的索引:users(role)id 列已有索引作为主键; name 有一个索引,因为它被声明为 unique.

对于前两种情况,limit 应该没有什么区别。如果没有 limit,引擎会在索引中找到匹配的行并 returns 它。如果引擎不使用 "unique" 信息,那么它可能需要查看索引中的下一个值,看看它是否相同。

第三种情况,没有索引,有点不同。如果没有索引,引擎将要扫描所有行以找到所有匹配项。使用索引,它可以在那里找到所有匹配的行。向其添加 limit,它会在第一个停止。

平均而言,与使用 limit 相比,适当的索引对性能的提升更大。