简体   繁体   English

如何在 LIKE 查询中返回子串位置

[英]How to return substring positions in LIKE query

I retrieve data from a MySQL database using a simple SELECT FROM WHERE LIKE case-insensitive query where I escape any % or _ in the like clause, so really the user can only perform basic text research and cannot mess up with regex because I then surround it myself with % in the LIKE clause.我使用一个简单的 SELECT FROM WHERE LIKE 不区分大小写的查询从 MySQL 数据库中检索数据,我在 like 子句中转义了任何%_ ,所以实际上用户只能执行基本的文本研究而不能搞乱正则表达式,因为我然后环绕它自己在 LIKE 子句中带有%

For every row returned by this query, I have to search again using a JS script in order to find all the indexes of the substring in the original string.对于此查询返回的每一行,我必须使用 JS 脚本再次搜索,以便找到原始字符串中子字符串的所有索引。 I dislike this method because I it's a different pattern matching than the one used by the LIKE query, I can't guarantee that the algorithm is the same.我不喜欢这种方法,因为它与 LIKE 查询使用的模式匹配不同,我不能保证算法相同。

I found MySQL functions POSITION or LOCATE that can achieve it, but they return only the first index if it was found or 0 if it was not found.我发现 MySQL 函数POSITIONLOCATE可以实现它,但如果找到,它们只返回第一个索引,如果没有找到,则返回 0。 Yes you can set the first index to search from, and by searching by passing the previously returned index as the first index until the new returned index is 0, you can find all indexes of the substring, but it means a lot of additional queries and it might end up slowing down my application a lot.是的,您可以设置要搜索的第一个索引,并且通过将先前返回的索引作为第一个索引进行搜索,直到新返回的索引为 0,您可以找到子字符串的所有索引,但这意味着很多额外的查询和它最终可能会大大降低我的应用程序速度。

So I'm now wondering: Is there a way to have the LIKE query to return substring positions directly, but I didn't find any because I lack MySQL vocabulary yet (I'm a noob).所以我现在想知道:有没有办法让LIKE查询直接返回子字符串位置,但我没有找到任何方法,因为我还没有 MySQL 词汇表(我是菜鸟)。

Simple answer: No.简单的回答:没有。

Longer answer: MySQL has no syntax or mechanism ot return an array of anything -- from either a SELECT or even a Stored Procedure.更长的答案:MySQL 没有从SELECT甚至存储过程返回任何数组的语法或机制。

Maybe answer: You could write a Stored procedure that loops through one result, finding the results and packing them into a commalist.也许答案:您可以编写一个存储过程来循环访问一个结果,找到结果并将它们打包到一个 commalist 中。 But I cringe at how messy that code would be.但我对代码会变得多么混乱感到畏缩。 I would quickly decide to write JS code, as you have already done.我会很快决定编写 JS 代码,就像您已经完成的那样。

Moral of the story: SQL is is not a full language.故事的寓意:SQL 不是一种完整的语言。 It's great at storing and efficiently retrieving large sets of rows , but lousy at string manipulation or arrays (other than "rows").它在存储和高效检索大量方面表现出色,但在字符串操作或数组(“行”除外)方面表现不佳。

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

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