Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Alternative zur LIKE-Klausel in Mysql

prod_catg LIKE '1,%' --matches when 1 is the first category
OR prod_catg LIKE '%,1,%' --matches when 1 is somewhere in the middle
OR prod_catg LIKE '%,1' --matches 1 when is the last category

Auf jeden Fall sollten Sie Ihr Schema umgestalten, indem Sie eine Kategorietabelle und den Verweis darauf in der Produkttabelle (Haupttabelle) hinzufügen

BEARBEITEN

Eine andere Möglichkeit, diesem Problem zu begegnen, ist die Verwendung von REGEXP was zu einem kürzeren WHERE führt -Klausel (hier ist, was ich zum Testen verwendet habe):

DECLARE @regexp VARCHAR(100);
SET @regexp = '^1,.*|.*,1$|.*,1,.*';

SELECT
    '1,11,15,51,22,31' REGEXP @regexp AS test1,
    '51,11,15,1,22,31' REGEXP @regexp AS test2,
    '11,15,51,22,31,1' REGEXP @regexp AS test3,
    '7,11,15,51,22,31' REGEXP @regexp AS test4,
    '51,11,15,7,22,31' REGEXP @regexp AS test5,
    '11,15,51,22,31,7' REGEXP @regexp AS test6;

dies wird mit Ihrem prod_catg übereinstimmen gegen den regulären Ausdruck '^1,.*|.*,1$|.*,1,.*' gibt 1 (TRUE) zurück wenn es übereinstimmt, 0 (FALSE) andernfalls.

Dann sieht Ihre WHERE-Klausel so aus:

WHERE prod_catg REGEXP '^1,.*|.*,1$|.*,1,.*'

Erklärung des regulären Ausdrucks:

^1,.* --matches 1 at the beginning of a string followed by a `,` and any other char
.*,1$ --matches 1 at the end of a string preceded by a `,` and any other char
.*,1,.* --matches 1 between two `,` which are sourrounded by any other chars
| --is the OR operator

Ich bin mir sicher, dass dieser reguläre Ausdruck viel kompakter sein könnte, aber ich bin nicht so gut mit regulären Ausdrücken

Natürlich können Sie die gesuchte Kategorie im regulären Ausdruck ändern (versuchen Sie, 1 zu ersetzen mit 7 am obigen Beispiel)