我有一个select语句,用于获取ID
上的值字段177,175,173,178,179
返回的内容是从null,单个条目到此字段中的多个逗号分隔值。
如何根据此逗号分隔字段使用SQL为每个值返回1行?
答案 0 :(得分:1)
正如评论中已经提到的那样,请考虑规范化您的数据,以便能够正常维护和查询您的数据。
与此同时,您可以在tally(number)表的帮助下实现纯SQL的目标,您可以像这样创建
CREATE TABLE tally (n INT NOT NULL PRIMARY KEY);
INSERT INTO tally
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
,(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
ORDER BY n;
现在你可能看起来像
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(value, ',', n), ',', -1) value
FROM table1 CROSS JOIN tally
WHERE id = 1
AND n <= 1 + (LENGTH(value) - LENGTH(REPLACE(value, ',', '')))
输出:
| VALUE | |-------| | 177 | | 175 | | 173 | | 178 | | 179 |
这是 SQLFiddle 演示