将枚举映射到MySQL中SUM的值/权重

将枚举映射到MySQL中SUM的值/权重,mysql,stored-procedures,enums,Mysql,Stored Procedures,Enums,我正在尝试创建一个类似以下内容的查询: SELECT id, SUM(my_column) FROM my_table GROUP BY my_column 其中,my_列不是数字,而是枚举 为了便于说明,假设它是一个小/中/大的尺寸,我希望小的值为1,中的值为10,大的值为100。如何将枚举映射到要在SUM函数中使用的整数 我一直在研究存储过程和CREATE函数语法,但我不确定这是否是要走的路线。基本上,如果我能创建这样的东西,那就太棒了,但我不知道如何在MySQL中实现它: SELECT

我正在尝试创建一个类似以下内容的查询:

SELECT id, SUM(my_column) FROM my_table GROUP BY my_column
其中,my_列不是数字,而是枚举

为了便于说明,假设它是一个小/中/大的尺寸,我希望小的值为1,中的值为10,大的值为100。如何将枚举映射到要在SUM函数中使用的整数

我一直在研究存储过程和CREATE函数语法,但我不确定这是否是要走的路线。基本上,如果我能创建这样的东西,那就太棒了,但我不知道如何在MySQL中实现它:

SELECT id, SUM(GET_VALUE_OF(my_column)) FROM my_table GROUP BY my_column;
其中GET_VALUE_的定义如下

GET_VALUE_OF = function(v) {
    switch(v) {
        case 'small': return 1;
        case 'medium': return 10;
        case 'large': return 100;
        default: return 0;
    }
}

您可以创建一个确定性函数:

delimiter $$
drop function if exists get_value_of$$
create function get_value_of(v varchar(50))
returns int deterministic
begin

    case v
      when 'small'  then return 1;
      when 'medium' then return 10;
      when 'large' then return 100;
      else  
        return 0;
    end case;

end$$
delimiter ;
您可以在查询中使用它:

mysql> select id, size , get_value_of(size) as val from my_table;
+----+--------+------+
| id | size   | val  |
+----+--------+------+
|  1 | small  |    1 |
|  2 | medium |   10 |
|  3 | large  |  100 |
|  4 | other  |    0 |
+----+--------+------+
4 rows in set (0.02 sec)
此外,在聚合功能中:

mysql> select sum(get_value_of(size)) as total from my_table;
+-------+
| total |
+-------+
|   111 |
+-------+
1 row in set (0.00 sec)