Question

I have a row with

(name1, name2, name3, name4)

AND another row with

(2, 3, 4, 5, 7)

I need to present that data in two columns, the name with the number in the same place like this:

NAMES  |  NUMBERS
--------------------
name1     2
name2     3
name3     4
name4     5

I tried with SUBSRTING_INDEX but I repaet the same number at first

Was it helpful?

Solution 2

I found the answer i used the function GROUP_CONCAT()

OTHER TIPS

I think in MySQL it might be done in a way similar to this:

CREATE TABLE t (names char(255), numbers char(255));
INSERT INTO t(names, numbers) VALUES('name1,name2,name3,name4', '2,3,5,7');

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.names, ',', idx), ',', -1),
       SUBSTRING_INDEX(SUBSTRING_INDEX(t.numbers, ',', idx), ',', -1)
FROM t, (select 1 idx union all select 2 union all select 3 union all select 4) r

Here is complete sqlfiddle

Sure, subquery generating number sequence should be adjusted to your case. There are a number of examples on stackoverflow how to achieve this particular task.

Update:

Here is an example how to handle up to 10000 elements in a row.

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.names, ',', idx), ',', -1),
       SUBSTRING_INDEX(SUBSTRING_INDEX(t.numbers, ',', idx), ',', -1)
FROM t,
(SELECT @row := @row + 1 AS idx FROM
(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) n,
(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) n2,
(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) n3,
(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) n4,
(SELECT @row:=0) n5
WHERE @row < (SELECT max(LENGTH(NAMES) - LENGTH(REPLACE(NAMES, ',', '')) + 1)
FROM t))r

Notice that to reduce amount of operations on strings we at first find maximum amount of elements in one row using a subquery.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top