如何在mysql查询中使用索引高效 [英] How to use index efficienty in mysql query

查看:178
本文介绍了如何在mysql查询中使用索引高效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库在mysql v5.x上运行。我有一个包含5列的表T1,而列C1是主键。 C1的类型为varchar(20)。它包含大约2000行,其值如下:

My db is running on mysql v5.x. I have a table T1 with 5 columns and column C1 is the primary key. C1 is of type varchar(20). It contains about 2000 rows with values like:

fxg
axt3
tru56
and so on.. 

现在我的应用程序的工作是读取输入数据并查找输入数据是否有启动模式类似于表T1中的C1列。例如:我的输入可能显示为:

Now my application's job is to read input data and find if the input data has a starting pattern similar to that found in column C1 in table T1. For example: my input may appear as:

    trx879478986
    fxg87698x84
    784xtr783utr
    axt3487ghty
... and so on

所以对于上面的输入,我必须返回true 'fxg87698x84'和'axt3487ghty'而其他人则为假。我使用的查询是:

So for the above input, I have to return true for 'fxg87698x84' and 'axt3487ghty' and false for others. The query I use is:

select 1 from T1 where (? like concat(C1,'%'));
note: the ? is replaced by the input value got from the application.

问题是我的输入很大(在30分钟内处理大约100万条记录)和我的查询速度不够快。有关如何重写查询或强制使用索引的任何想法?即使我必须使用不同的对象结构,我也能做到,如果这有帮助的话。所以任何帮助将不胜感激。 Thx。

The issue is my input is huge (about 1 million records to be processed in 30 minutes) and my query is not fast enough. Any ideas on how to re-write the query or force it to use indexes? Even if I have to use a different object structure, I can do it, if that helps. So any help will be appreciated. Thx.

推荐答案

您可以尝试使用Top-N查询来查找第一个候选项,然后将该候选项仅应用于实际模式:

you could try a Top-N query to find the first candidate, and then apply that candidate only to the actual pattern:

select 1 
  from (select c1 
          from junk 
         where c1 <= 'fxg87698x84'
         order by c1 desc limit 1) tmp 
 where 'fxg87698x84' like concat(c1, '%');

top-n查询应该在c1上使用常规索引。

the top-n query should use a regular index on c1.

编辑
在我的博客中详细解释: http://blog.fatalmind.com/2010/09/29/finding-the-best-match-with -a-top-n-query /

这篇关于如何在mysql查询中使用索引高效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆