Last active
October 2, 2015 13:52
-
-
Save hiropppe/aff05b39921bd6195be8 to your computer and use it in GitHub Desktop.
MySQL function which behaves like zip function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE FUNCTION `zip`(_first text, _second text, _separator text, _pair_separator text) RETURNS text CHARSET utf8 | |
BEGIN | |
DECLARE _ret text; | |
IF 0 < LENGTH(_first) THEN | |
SELECT | |
GROUP_CONCAT( | |
CONCAT_WS( | |
_pair_separator, | |
REPLACE(SUBSTRING_INDEX(v.`first`, _separator, p.rownum), CONCAT(SUBSTRING_INDEX(v.`first`, _separator, p.rownum - 1), _separator), ''), | |
REPLACE(SUBSTRING_INDEX(v.`second`, _separator, p.rownum), CONCAT(SUBSTRING_INDEX(v.`second`, _separator, p.rownum - 1), _separator), '') | |
) | |
SEPARATOR ' ' | |
) | |
INTO | |
_ret | |
FROM | |
( SELECT | |
_first `first` | |
, _second `second` | |
, LENGTH(_first) - LENGTH(REPLACE(_first, _separator, '')) + 1 `num_element` | |
) v | |
INNER JOIN pivot p | |
ON p.rownum <= v.num_element | |
; | |
END IF; | |
RETURN _ret; | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
requires pivot table.
mysql> select * from pivot;
+--------+
| rownum |
+--------+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
+--------+
5 rows in set (0.01 sec)
mysql> select zip('a,b,c', '1,2,3', ',', '-');
+----------------------------------------+
| zip('a,b,c', '1,2,3', ',', '-') |
+----------------------------------------+
| a-1 b-2 c-3 |
+----------------------------------------+
1 row in set (0.01 sec)
mysql> select zip('a b c', '1 2 3', ' ', ',');
+----------------------------------------+
| zip('a b c', '1 2 3', ' ', ',') |
+----------------------------------------+
| a,1 b,2 c,3 |
+----------------------------------------+
1 row in set (0.00 sec)