如何在mysql查询中使用索引高效

编程入门 行业动态 更新时间:2024-10-27 18:31:19
本文介绍了如何在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.

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

更多推荐

如何在mysql查询中使用索引高效

本文发布于:2023-10-21 17:06:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1514824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:高效   索引   如何在   mysql

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!