繁体   English   中英

MySQL 性能:查询索引列是否具有给定值

[英]MySQL performance: query if an indexed column has a given value

鉴于表

create table t (
  t_id int not null primary key,
  c int not null,
  ...
  key (c)
)

我想查询t中的任何行是否有c等于 X。我只需要一个是/否的答案。

由于列c已编入索引,因此 MySQL 应该能够在索引中查找并在找到一个值 X 后立即停止。哪些查询将从 MySQL 中获得最佳性能?

你有比我更好的想法吗?

select 1 from t where c=X limit 1

或者

select count(*)>0 from t where c=X

我更喜欢前者。 后者似乎需要优化器更多的聪明才智。

您的限制 1 方法很好,因为使用存在:

select exists (select 1 from t where c = x)

绝对不计较。 这样做会使它在应用 > 0 条件之前实际计算所有匹配的行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM