gpt4 book ai didi

MySQL 每列的最小值和最大值

转载 作者:行者123 更新时间:2023-11-29 11:32:55 25 4
gpt4 key购买 nike

我可以运行以下命令来动态识别具有多列的表中的所有小数字段:

SELECT COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tbl_name' AND DATA_TYPE = 'decimal'

我如何提取每个字段的最小值和最大值?例如最终输出如下:

COLUMN_NAME  DATA_TYPE  MIN_VAL  MAX_VAL
a decimal 4 22
b decimal 18 5593
c decimal 1 299
<小时/>

更新:

这是我用来实现此功能的最终语法。也许我错过了一个更简单的方法,但这是有效的,所以感谢戈登·利诺夫的回答。

set @sql = concat('SELECT ', @cols, ' FROM ', @t);

SELECT @sql := GROUP_CONCAT(REPLACE(REPLACE(@sql, @cols,
CONCAT('"', COLUMN_NAME, '" as TheCol', ', ', '"', DATA_TYPE, '" as TheDType', ', ',
'MIN(', COLUMN_NAME, ') as TheMin, MAX(', COLUMN_NAME, ') as TheMax'
)
),
@t, 'tbl_name') SEPARATOR ' union all '
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tbl_name' AND DATA_TYPE = 'decimal';

prepare s from @sql;
execute s;
deallocate prepare s;

最佳答案

您需要使用动态sql:

set @sql = 'SELECT @cols FROM @t';

SELECT @sql := GROUP_CONCAT(REPLACE(REPLACE(@sql, @cols,
CONCAT(COLUMN_NAME, ', ', DATA_TYPE, ', ',
'MIN(', COLUMN_NAME, '), MAX(', COLUMN_NAME, ')'
)
),
@t, 'tbl_name') SEPARATOR ' union all '
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='tbl_name' AND DATA_TYPE = 'decimal';

prepare s from @sql;
execute s;
deallocate prepare s;

关于MySQL 每列的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37102279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com