Skip to content

Instantly share code, notes, and snippets.

@hiropppe
Last active October 2, 2015 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiropppe/aff05b39921bd6195be8 to your computer and use it in GitHub Desktop.
Save hiropppe/aff05b39921bd6195be8 to your computer and use it in GitHub Desktop.
MySQL function which behaves like zip function.
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
@hiropppe
Copy link
Author

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment