Mi piacerebbe trovare un modo elegante per emulare il comportamento della funzione subtring_index() di MySQL in Postgres.emulazione di substring_index() di MySQL in PGSQL
In MySQL, è facile come:
mysql> create temporary table test1(test varchar(200));
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test1 values('apples||oranges'),('apples||grapes');
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select * from test1;
+-----------------+
| test |
+-----------------+
| apples||oranges |
| apples||grapes |
+-----------------+
2 rows in set (0.00 sec)
mysql> select substring_index(test, '||', 1) as field1, substring_index(test, '||', -1) as field2 from test1;
+--------+---------+
| field1 | field2 |
+--------+---------+
| apples | oranges |
| apples | grapes |
+--------+---------+
2 rows in set (0.00 sec)
Ma il mio lavoro attuale in giro in PGSQL è abbastanza brutto:
hoth=# create temporary table test1(test text);
CREATE TABLE
hoth=# insert into test1 values('apples||oranges'),('apples||grapes');
INSERT 0 2
hoth=# select * from test1;
test
-----------------
apples||oranges
apples||grapes
(2 rows)
hoth=# select substring(test, 0, position('||' in test)) as field1, substring(test, position('||' in test) + 2, char_length(test)) as field2 from test1;
field1 | field2
--------+---------
apples | oranges
apples | grapes
(2 rows)
forse c'è una soluzione più elegante utilizzando un'espressione regolare, o forse anche suddividendo la stringa in una matrice in una variabile che potrebbe ridurre il sovraccarico se la stringa deriva da una sottoquery o qualcosa del genere, accolgo con favore qualsiasi suggerimento.
Suppongo che la soluzione al di fuori-the-box è quello di memorizzare i dati in un modo che è più suscettibili alle domande che si desidera eseguire (ad esempio normalizzando o usando un tipo di matrice). Mi rendo conto che non è sempre un'opzione, ma ho pensato di buttarla lì, in particolare perché il tuo esempio MySQL sembra essere specificamente codificato per la suddivisione in esattamente 2 parti. – IMSoP