Ricerca nel sito web

Come tagliare parte di una stringa con una query MySQL?


Per questo, usa la funzione substring_index() di MySQL. Creiamo innanzitutto una tabella:

mysql> create table DemoTable
   -> (
   -> StudentId varchar(100)
   -> );
Query OK, 0 rows affected (0.60 sec)

Inserisci alcuni record nella tabella utilizzando il comando di inserimento:

mysql> insert into DemoTable values('STU-1011');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable values('STU-95968686');
Query OK, 1 row affected (0.17 sec)

Visualizza tutti i record dalla tabella utilizzando l'istruzione select :

mysql> select *from DemoTable;

Ciò produrrà il seguente output:

+--------------+
| StudentId    |
+--------------+
| STU-1011     |
| STU-95968686 |
+--------------+
2 rows in set (0.00 sec)

Di seguito è riportata la query per tagliare parte di una stringa in MySQL prima del trattino (-):

mysql> select substring_index(substring(StudentId, instr(StudentId, "-")+1), " ", 1) from DemoTable;

Ciò produrrà il seguente output che visualizzerà parte della stringa prima del trattino (-)

+------------------------------------------------------------------------+
| substring_index(substring(StudentId, instr(StudentId, "-")+1), " ", 1) |
+------------------------------------------------------------------------+
| 1011                                                                   |
| 95968686                                                               |
+------------------------------------------------------------------------+
2 rows in set (0.02 sec)

Articoli correlati: