我在Mysql中有CONV函数:
mysql> CONV(26,10,26)
-> 10
但我想要这样的事情:
mysql> CONV_LETTERS(26,10,26)
-> aa
如何将MySQL从基数10转换为基数26,但只使用字母使数字26成为aa?
更新
我到目前为止:
delimiter //
CREATE PROCEDURE `base10_to_base26_letters`(IN `nr` BIGINT)
BEGIN
SET @letters='abcdefghijklmnopqrstuvwxyz';
select SUBSTRING(@letters,`nr`+1,1);
END//
更新2
尝试将this php函数转换为MySQL过程。
PHP函数:
function generateAlphabet($na) {
$sa = "";
while ($na >= 0) {
$sa = chr($na % 26 + 65) . $sa;
$na = floor($na / 26) - 1;
}
return $sa;
}
到目前为止我的MySQL程序:
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//
为什么我只为我试过的任何号码获得z?
答案 0 :(得分:1)
我们在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;
}
答案 1 :(得分:0)
此存储函数将单个int转换为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 ;