From base 10 to base 26 only with letters so that

2020-03-28 17:54发布

I have the CONV function in Mysql:

mysql> CONV(26,10,26)
      -> 10

But I want something like this:

mysql> CONV_LETTERS(26,10,26)
      -> aa

How can I convert in MySQL from base 10 to base 26, but only use letters so that number 26 will become aa?

UPDATE

I got so far:

delimiter //
CREATE PROCEDURE `base10_to_base26_letters`(IN `nr` BIGINT)
BEGIN

SET @letters='abcdefghijklmnopqrstuvwxyz';
select SUBSTRING(@letters,`nr`+1,1);

END//

UPDATE 2

Trying to convert this php function to MySQL procedure.

The PHP function:

function generateAlphabet($na) {
    $sa = "";
    while ($na >= 0) {
        $sa = chr($na % 26 + 65) . $sa;
        $na = floor($na / 26) - 1;
    }
    return $sa;
}

My MySQL procedure so far:

delimiter //
CREATE PROCEDURE `base10_to_base26_letters`(IN `nr` BIGINT)
BEGIN

SET @n=`nr`,@letters='abcdefghijklmnopqrstuvwxyz',@r='';
while @n>=0 do
set @n=@n/26-1,@r=concat(SUBSTRING(@letters,@n%26,1),@r);
end while;
select @r;

END//

Why I only get z for any number I tried?

2条回答
够拽才男人
2楼-- · 2020-03-28 18:36

We are doing this in PHP:

private function numToB26($num)
{
    /* $num++; // Uncomment to use "Excel"-mapping, e.g. 1=A instead of 0=A */
    do {
        $val = ($num % 26) ?: 26;
        $num = ($num - $val) / 26;
        $b26 = chr($val + 64).($b26 ?: '');
    } while (0 < $num);
    return $b26;
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-03-28 18:55

This stored function converts a single int to base26:

DROP FUNCTION IF EXISTS `base10to26`;
DELIMITER ;;

CREATE FUNCTION `base10to26`(`theNumber` INT(11) UNSIGNED) 
RETURNS VARCHAR(20) READS SQL DATA
BEGIN
    DECLARE colTxt VARCHAR(20);
    DECLARE value  INT(11);
    SET colTxt = '';

    REPEAT
        SET value  = theNumber % 26;
        IF value = 0 THEN SET value = 26; END IF;
        SET theNumber = (theNumber - value) / 26;
        SET colTxt = CONCAT(CHAR(value+64), colTxt);
    UNTIL theNumber = 0 END REPEAT;

    RETURN colTxt;
END;;
DELIMITER ;
查看更多
登录 后发表回答