MYSQL:如何使用连接字符串作为列名来遍历 table 列?
MYSQL: How could I iterate over table columns using a concatenated string as column name?
我正在寻找一种方法来循环遍历 MYSQL table 中的列,使用连接的字符串来索引循环中的列名称。 table 中的数据示例可能如下所示:
R1 R2 R3 R4
0.68 0.08 0.04 4.24
0.15 1.17 3.06 0.57
1.59 0.48 1.39 1.00
1.59 0.77 1.13 0.22
0.90 0.23 0.73 0.52
列名只是字符 "R" 和一个数字(最终列数会有所不同,因此数字最多可达 100)。我想遍历列以计算每列中超过阈值的值的数量(我使用三个阈值:3.0、5.0 和 10.0)。调用该过程的结果应类似于以下内容:
str2 total ThreeCount FiveCount TenCount
`R1` 8772 794 153 1
str2 total ThreeCount FiveCount TenCount
`R2` 8772 382 42 0
等等
我一直在使用以下代码作为存储过程来测试该过程(我使用 5 进行测试,因此迭代了前五列数据值):
BEGIN
DECLARE x INT;
DECLARE str1 VARCHAR(1);
DECLARE str2 VARCHAR(5);
DECLARE str3 VARCHAR(1);
SET x = 1;
SET str1 = "R";
SET str2 = "";
SET str3 = "`";
WHILE x <= 5 DO
SET str2 = CONCAT(str3,str1,x,str3);
select str2,
count(*) total,
sum(case when str2 > 3.0 then 1 else 0 end) ThreeCount,
sum(case when str2 > 5.0 then 1 else 0 end) FiveCount,
sum(case when str2 > 10.0 then 1 else 0 end) TenCount
from test_dat;
SET x = x + 1;
END WHILE;
END
但是程序 returns 零值(总数除外)除非我用实际的列名替换 "str2"(例如用 R1
、R2
替换 str2 ETC)。但是我宁愿不使用实际的列名。
如何将连接的字符串 (str2) 识别为列名?我尝试了各种串联组合,例如:
SET str2 = CONCAT(str1,x);
但是这些都没有得到非零计数。
感谢您提供的任何帮助。
标准化设计可能看起来像这样
id r val
1 1 0.68
2 1 0.15
3 1 1.59
4 1 1.59
5 1 0.90
6 2 0.08
7 2 1.17
8 2 0.48
9 2 0.77
10 2 0.23
11 3 0.04
12 3 3.06
13 3 1.39
14 3 1.13
15 3 0.73
16 4 4.24
17 4 0.57
18 4 1.00
19 4 0.22
20 4 0.52
我正在寻找一种方法来循环遍历 MYSQL table 中的列,使用连接的字符串来索引循环中的列名称。 table 中的数据示例可能如下所示:
R1 R2 R3 R4
0.68 0.08 0.04 4.24
0.15 1.17 3.06 0.57
1.59 0.48 1.39 1.00
1.59 0.77 1.13 0.22
0.90 0.23 0.73 0.52
列名只是字符 "R" 和一个数字(最终列数会有所不同,因此数字最多可达 100)。我想遍历列以计算每列中超过阈值的值的数量(我使用三个阈值:3.0、5.0 和 10.0)。调用该过程的结果应类似于以下内容:
str2 total ThreeCount FiveCount TenCount
`R1` 8772 794 153 1
str2 total ThreeCount FiveCount TenCount
`R2` 8772 382 42 0
等等
我一直在使用以下代码作为存储过程来测试该过程(我使用 5 进行测试,因此迭代了前五列数据值):
BEGIN
DECLARE x INT;
DECLARE str1 VARCHAR(1);
DECLARE str2 VARCHAR(5);
DECLARE str3 VARCHAR(1);
SET x = 1;
SET str1 = "R";
SET str2 = "";
SET str3 = "`";
WHILE x <= 5 DO
SET str2 = CONCAT(str3,str1,x,str3);
select str2,
count(*) total,
sum(case when str2 > 3.0 then 1 else 0 end) ThreeCount,
sum(case when str2 > 5.0 then 1 else 0 end) FiveCount,
sum(case when str2 > 10.0 then 1 else 0 end) TenCount
from test_dat;
SET x = x + 1;
END WHILE;
END
但是程序 returns 零值(总数除外)除非我用实际的列名替换 "str2"(例如用 R1
、R2
替换 str2 ETC)。但是我宁愿不使用实际的列名。
如何将连接的字符串 (str2) 识别为列名?我尝试了各种串联组合,例如:
SET str2 = CONCAT(str1,x);
但是这些都没有得到非零计数。
感谢您提供的任何帮助。
标准化设计可能看起来像这样
id r val
1 1 0.68
2 1 0.15
3 1 1.59
4 1 1.59
5 1 0.90
6 2 0.08
7 2 1.17
8 2 0.48
9 2 0.77
10 2 0.23
11 3 0.04
12 3 3.06
13 3 1.39
14 3 1.13
15 3 0.73
16 4 4.24
17 4 0.57
18 4 1.00
19 4 0.22
20 4 0.52