简体   繁体   English

可以在没有表重组的情况下优化此查询吗

[英]Can this query be optimized without table restructuring?

SELECT * FROM products WHERE
serial LIKE '{$ssz}'             //exact match, no other serials in row
OR serial LIKE '%,{$ssz}'        //match at list end
OR serial LIKE '%,{$ssz},%'      //match between other two serials
OR serial LIKE '{$ssz},%'        //match at list beginning

This is my perfectly working query, where {$ssz} is a PHP variable to search for. 这是我完美的查询,其中{$ ssz}是要搜索的PHP变量。 serial TEXT columns contain a list of serial numbers, separated with comma. serial TEXT列包含序列号列表,以逗号分隔。

The serials are unique, but variable length, so "AAB001" and "AB001" are possible. 连续出版物是唯一的,但长度可变,因此“AAB001”和“AB001”是可能的。

Maybe it would be faster with regex? 也许正则表达式更快? Or with a totally different approach? 或者采用完全不同的方法?

You can shorten it to: 您可以将其缩短为:

SELECT p.*
FROM products p
WHERE FIND_IN_SET('{$ssz}', serial) > 0;

This is nicer to look at and easier to code. 这样看起来更好,更容易编码。 But it is not substantially faster. 但它并没有快得多。

What is the issue? 有什么问题? Your data model is the issue. 您的数据模型是个问题。 You should not be storing lists of things in a delimited string. 您不应该在分隔的字符串中存储事物列表。 SQL has this really great way to store lists. SQL有这种存储列表的好方法。 It is called a table not a string. 它被称为而不是字符串。

You need a junction/association table for your data. 您需要一个用于数据的联结/关联表。 Then you can speed the query using appropriate indexes. 然后,您可以使用适当的索引加快查询速度。

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

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