SQL >> Database >  >> RDS >> Mysql

Hoe de LOCATE()-functie werkt in MySQL

De MySQL-functie LOCATE() retourneert de positie van een subtekenreeks binnen een tekenreeks. U kunt ook een startpositie opgeven.

Syntaxis

LOCATE(substr,str)
LOCATE(substr,str,pos)

substr is de gezochte subtekenreeks, str de doorzochte tekenreeks en pos de optionele startpositie.

Voorbeeld 1 – Eerste vorm

SELECT LOCATE('cat', 'One cat jumped over the other cat') AS Result;

Resultaat:

+--------+
| Result |
+--------+
| 5      |
+--------+

Voorbeeld 2 – Tweede vorm

SELECT LOCATE('cat', 'One cat jumped over the other cat', 6) AS Result;

Resultaat:

+--------+
| Result |
+--------+
| 31     |
+--------+

De functie retourneert altijd de positie in de hele tekenreeks, niet de offset vanaf de startpositie.

Voorbeeld 3 – Deel van een woord

SELECT LOCATE('sing', 'Increasingly') AS Result;

Resultaat:

+--------+
| Result |
+--------+
| 7      |
+--------+

Voorbeeld 4 – Geen overeenkomst

SELECT LOCATE('Bat', 'Increasingly') AS Result;

Resultaat:

+--------+
| Result |
+--------+
| 0      |
+--------+

Voorbeeld 5 – Hoofdlettergevoeligheid

De functie is hoofdletterongevoelig, tenzij een argument binair is.

SET @str = BINARY 'Increasingly';
SELECT LOCATE('Sing', @str) AS Result;

Resultaat:

+--------+
| Result |
+--------+
| 0      |
+--------+

Voorbeeld 6 – NULL-argumenten

SELECT LOCATE(NULL, 'Increasingly') a,
       LOCATE('Bat', NULL) b,
       LOCATE('Bat', 'Increasingly', NULL) c;

Resultaat:

+------+------+------+
| a    | b    | c    |
+------+------+------+
| NULL | NULL | NULL |
+------+------+------+
  1. Hoe de LTRIM()-functie werkt in MySQL

  2. Hoe de RPAD()-functie werkt in MySQL

  3. Hoe de LPAD()-functie werkt in MySQL

  4. Hoe de RIGHT()-functie werkt in MySQL