emulating MySQL's substring_index() in PGSQL

后端 未结 2 1800
离开以前
离开以前 2021-01-17 16:51

I would like to find an elegant way to emulate the behavior of MySQL\'s subtring_index() function in Postgres.

In MySQL, it\'s as easy as:

mysql>         


        
2条回答
  •  暖寄归人
    2021-01-17 17:09

    Here is how I implement (or emulate) MySQL's subtring_index() in PostgreSQL

    CREATE OR REPLACE FUNCTION public.substring_index (
      str text,
      delim text,
      count integer = 1,
      out substring_index text
    )
    RETURNS text AS
    $body$
    BEGIN
      IF count > 0 THEN
        substring_index = array_to_string((string_to_array(str, delim))[:count], delim);
      ELSE
        DECLARE
          _array TEXT[];
        BEGIN
          _array = string_to_array(str, delim);
          substring_index = array_to_string(_array[array_length(_array, 1) + count + 1:], delim);    
        END;  
      END IF;
    END;
    $body$
    LANGUAGE 'plpgsql'
    IMMUTABLE
    CALLED ON NULL INPUT
    SECURITY INVOKER
    COST 5;
    

    and here is the example from mysql's documentation;

    postgres=# SELECT substring_index('www.mysql.com', '.', 2);
     substring_index
    -----------------
     www.mysql
    (1 row)
    
    postgres=# SELECT substring_index('www.mysql.com', '.', -2);
     substring_index
    -----------------
     mysql.com
    (1 row)
    

提交回复
热议问题