Mysql将int转换为MAC

sai*_*101 3 mysql int function

我有一些数据转换,其中有2列,一列有IP,它包含整数值.我在我的mysql查询中使用了以下函数.有一个函数,我可以用来转换我的mac列,其中包含整数和数据类型对于MAC地址是bigint.

SELECT  INET_NTOA(ip_address) AS myip,mymac 
FROM table1
Run Code Online (Sandbox Code Playgroud)

Raz*_*scu 5

假设您通过抑制所有分隔符并将生成的HEX数转换为int来存储MAC地址,则从此int到人类可读MAC地址的转换将是:

function int2macaddress($int) {
    $hex = base_convert($int, 10, 16);
    while (strlen($hex) < 12)
        $hex = '0'.$hex;
    return strtoupper(implode(':', str_split($hex,2)));
}
Run Code Online (Sandbox Code Playgroud)

该功能取自http://www.onurguzel.com/storing-mac-address-in-a-mysql-database/

这个函数的MySQL版本:

delimiter $$
create function itomac (i BIGINT)
    returns char(20) 
    language SQL
begin
    declare temp CHAR(20);
    set temp = lpad (hex (i), 12, '0');
    return concat (left (temp, 2),':',mid(temp,3,2),':',mid(temp,5,2),':',mid(temp,7,2),':',mid(temp,9,2),':',mid(temp,11,2));
end;
$$
delimiter ;
Run Code Online (Sandbox Code Playgroud)

您也可以直接在SQL中执行此操作,如下所示:

select
    concat (left (b.mh, 2),':',mid(b.mh,3,2),':',mid(b.mh,5,2),':',mid(b.mh,7,2),':',mid(b.mh,9,2),':',mid(b.mh,11,2))
from (
    select lpad (hex (a.mac_as_int), 12, '0') as mh
    from (
        select 1234567890 as mac_as_int
    ) a
) b
Run Code Online (Sandbox Code Playgroud)