使用SQL查询在列中分隔行

时间:2014-03-23 08:32:30

标签: php sql split substring rows

我有一行

(name1, name2, name3, name4)

另一行

(2, 3, 4, 5, 7)

我需要将这些数据呈现在两列中,名称与数字在同一位置,如下所示:

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

我尝试使用SUBSRTING_INDEX,但我先修复了相同的号码

2 个答案:

答案 0 :(得分:2)

我认为在MySQL中可能会以类似的方式完成:

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

完成sqlfiddle

当然,应根据您的情况调整子查询生成数字序列。 stackoverflow上有很多关于如何实现这个特定任务的例子。

<强>更新

以下是如何连续处理多达10000个元素的示例。

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

请注意,为减少对字符串的操作量,我们首先使用子查询查找一行中的最大元素数量。

答案 1 :(得分:0)

我找到了答案,我使用了函数GROUP_CONCAT()