在 Redshift 中将 MD5 输出转换为 32 位整数

Convert the MD5 output into 32 bit integer in Redshift

我在 Redshift 中尝试了以下方法

SELECT STRTOL(MD5('345793260804895811'), 10);

但我得到了以下 DBCException:

SQL Error [22023]: ERROR: The input cf82576a6dbf9ff63cf9828f990f0673 is not valid to be converted to base 10

org.postgresql.util.PSQLException: PSQLException: ERROR: The input cf82576a6dbf9ff63cf9828f990f0673 is not valid to be converted to base 10

如何在 Redshift 中完成此操作?

MD5 的结果是 128 位长(ref),你不能将它放入 32 位整数中。

您有 2 个问题:

  • 首先,您需要指定转换为 base 16
  • 其次,MD5 字符串会大量溢出 64 位 BIGINT

效果很好

SELECT STRTOL(LEFT(MD5('345793260804895811'),15), 16);

将 MD5 十六进制值缩短为最左边的 15 个字符,并使用基数 16 转换为 BIGINT

您可以尝试使用 16 进制而不是 10 进制进行转换:

SELECT STRTOL(MD5('cf82576a6dbf9ff63cf9828f990f0673'), 16);

我想到了将 MD5 存储在两个 BIGINT 字段中而不是 CHAR(32) - 节省 2 倍 space!

select 
    convert(bigint,
        strtol(substring(hash,1,8),16) * 4294967296.0 +
        strtol(substring(hash,9,8),16) - 9223372036854775807
    ) as hash_part1
    ,convert(bigint,
        strtol(substring(hash,17,8),16) * 4294967296.0 +
        strtol(substring(hash,25,8),16) - 9223372036854775807
    ) as hash_part2

希望对大家有所帮助。