简体   繁体   中英

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. serial TEXT columns contain a list of serial numbers, separated with comma.

The serials are unique, but variable length, so "AAB001" and "AB001" are possible.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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