我有一个MySQL列,其中有一组用空格分隔的数字。大约有330个空间.....并且它们并非都在同一个地方(每一组) 有没有办法可以自动执行此操作,例如通过查询? 或者这可能在Microsoft SQL中吗?
编辑1:我担心我没有真正尝试过任何事情, - 不确定该怎么做。 以下是其中一组数字的示例
3 10 13 18 0 0 175 215 177 173 213 203 592 272 0 175 215 177 173 215 177 172 208 203 592
这是非常重复的。
答案 0 :(得分:1)
您可以生成一个数字列表,然后使用SUBSTRING_INDEX对数据进行交叉连接以获取各个字段。
这样的事情: -
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(SomeField, ' ', aNum + 1), ' ', -1)
FROM SomeTable
CROSS JOIN
(
SELECT Units.aCnt + Tens.aCnt * 10 + Hundreds.aCnt * 100 AS aNum
FROM
(SELECT 0 AS aCnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Units,
(SELECT 0 AS aCnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Tens,
(SELECT 0 AS aCnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Hundreds
) Sub1
WHERE LENGTH(SomeField) - LENGTH(REPLACE(SomeField, ' ', '')) >= aNum
SQL小提琴: -
http://www.sqlfiddle.com/#!2/7c43a/4
然后找到设计数据库表的人并向他们解释数据库设计/规范化/索引。
编辑 - 一种可以(几乎)做这个选择的方法,应对cols的数量。对于该行不存在的任何col,它应该返回NULL。可能最适合在MySQL存储过程中使用。它计算最大cols数,然后生成一些动态SQL来获取cols。
SET @sql = NULL;
SET SESSION group_concat_max_len = 1000000;
SELECT GROUP_CONCAT(aField ORDER BY aNum)
INTO @sql
FROM
(
SELECT (Units.aCnt + Tens.aCnt * 10 + Hundreds.aCnt * 100) AS aNum, CONCAT("IF(LENGTH(SomeField) - LENGTH(REPLACE(SomeField, ' ', '')) >= ", (Units.aCnt + Tens.aCnt * 10 + Hundreds.aCnt * 100), ", SUBSTRING_INDEX(SUBSTRING_INDEX(SomeField, ' ', ", (Units.aCnt + Tens.aCnt * 10 + Hundreds.aCnt * 100 + 1),"), ' ', -1), NULL) AS col",(Units.aCnt + Tens.aCnt * 10 + Hundreds.aCnt * 100)) AS aField
FROM (SELECT MAX(LENGTH(SomeField) - LENGTH(REPLACE(SomeField, ' ', ''))) AS MaxDelim FROM SomeTable) Sub1,
(SELECT 0 AS aCnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Units,
(SELECT 0 AS aCnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Tens,
(SELECT 0 AS aCnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Hundreds
WHERE Units.aCnt + Tens.aCnt * 10 + Hundreds.aCnt * 100 <= Sub1.MaxDelim
) Sub2;
SET @sql = CONCAT('SELECT ', @sql,
' FROM SomeTable
');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SQL小提琴: -