mysql inet6 aton,INET6_ATON的替代MySQL代码

Convert old INET_ATON value to new binary INET6_ATON value without INET6_ATON / INET6_NTOA

We have existing data in a table, the field is of type UNSIGNED INT which holds IPv4 data which was created with INET_ATON().

But now we move to INET6_ATON() in the queries and want to migrate the data diectly without creating additional database fields for the conversion.

So I changed the field type from UNSIGNED INT to VARBINARY(16).

New data is stored as binary value with INET6_ATON().

But how can we convert the old data?

I already tried to cast the existing values to integer and convert them to with HEX. This gives me the same hex string when saving it with INET6_ATON().

Did I miss some step or some literal?

UPDATE visitors SET ip = HEX(CAST(ip AS UNSIGNED))

The binary data is not the same. In this case it is saved as hex value. Using BIN(), CONVERT() and CAST() did not help.

Example data:

old ip value in unsigned int field:

2130706433 ( = ip2long('127.0.0.1') )

old value as shown in varbinary field:

32313330373036343333 ( = 2130706433 )

new value as shown in varbinary field:

7f000001 ( = INET6_ATON('127.0.0.1') )

We can not directly use INET6_ATON() / INET6_NTOA() for conversion.

Should we convert the data for every row with the PHP functions inet_top() and inet_pton() or is there a pure SQL solution for this without the need for some UDF so all rows are updated at once?

It seems there was already a similar question but there is no solution and the solution mentioned in the comments procudes wrong data and does not provide some working example code: Convert IPv6 to binary without INET6_ATON()

解决方案

I found the solution.

With an UPDATE query we can fetch the original value from the database, cast it to int again, hex and unhex it (can this be further shortened?) and we get the right binary value in the database.

UPDATE table SET ip = UNHEX(HEX(CAST(ip AS UNSIGNED)))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值