答案 0 :(得分:0)
当问题标记为MySQL时提供此答案。
您的预期结果要求fieldname与FootnoteID之间存在一对一的关系,因此找到一个连续colunm的每个部分的逻辑与第二个所需的逻辑相同。换句话说:如果您的数据在逗号分隔的列中具有相同数量的部分,则可以使用单个方法来分割两者:
CREATE TABLE Table1
(`EntryNum` int, `FieldNames` varchar(22), `FootnoteIDs` varchar(12))
;
INSERT INTO Table1
(`EntryNum`, `FieldNames`, `FootnoteIDs`)
VALUES
(1, 'FieldA, FieldA, FieldB', 'F1, F3, F2'),
(2, 'FieldA, FieldA, FieldB', 'F1, F4, F2'),
(3, 'FieldB, FieldC, FieldD', 'F1, F12, F13')
;
查询1 :
SELECT
t.EntryNum
, SUBSTRING_INDEX(SUBSTRING_INDEX(t.FieldNames, ',', n.n), ',', -1) FieldName
, SUBSTRING_INDEX(SUBSTRING_INDEX(t.FootnoteIDs, ',', n.n), ',', -1) FootnoteID
FROM table1 t
CROSS JOIN (
SELECT a.N + b.N * 10 + 1 n
FROM (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
CROSS JOIN (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
) n
WHERE n.n <= 1 + (LENGTH(t.FieldNames) - LENGTH(REPLACE(t.FieldNames, ',', '')))
order by t.EntryNum, n.n
请参阅此SQL Fiddle
| EntryNum | FieldName | FootnoteID |
|----------|-----------|------------|
| 1 | FieldA | F1 |
| 1 | FieldA | F3 |
| 1 | FieldB | F2 |
| 2 | FieldA | F1 |
| 2 | FieldA | F4 |
| 2 | FieldB | F2 |
| 3 | FieldB | F1 |
| 3 | FieldC | F12 |
| 3 | FieldD | F13 |
注意上面的查询是SQL split comma separated row的答案的衍生物,该答案指的是永久“计数表”而不是动态子查询(n)的好处上方。