mysql 中身份证字段脱敏

阿里云产品限时红包,最高 ¥1888 元,立即领取

在数据的使用与传输过程中,经常需要将敏感信息脱敏的过程。比如需要将用户信息表中的身份证号码中间 几位进行隐藏等等。

脱敏方法

mysql 中常用的脱敏方法有以下两种。

CONCAT()、LEFT() 和 RIGHT() 字符串函数组合使用

  • CONCAT(str1, str2, …):返回结果为连接参数产生的字符串
  • LEFT(str, len):返回从字符串 str 开始的最左 len 字符
  • RIGHT(str, len):从字符串 str 开始,返回最右 len 字符
1
2
3
SELECT 
CONCAT(LEFT(identity_card_no, 6), '********' , RIGHT(identity_card_no, 4))
FROM users;

INSERT()

  • INSERT(str, pos, len, newstr):返回字符串 str, 其子字符串起始于 pos 位置和长期被字符串 newstr 取代的 len 字符
1
2
3
SELECT
INSERT(identity_card_no, 7, 8, '********')
FROM users;

从查询结果中更新数据

# update select 语句(注意:必须使用 inner join)
# 语法 update ta inner join (select yy from tb) tc on ta.id = tc.id set ta.xx = tc.yy

-- 行政处罚信息表
UPDATE T_XYXX_XZCFXX ori
INNER JOIN (
SELECT
  uuid,
  INSERT ( FDDBR, 1, 1, '*' ) AS NAME,
  CONCAT(
  '000000',
  '****',
  RIGHT ( FDDBRZJHM, 8 ) 
  ) AS idcardno 
FROM
  T_XYXX_XZCFXX 
  ) nosense ON ori.uuid = nosense.uuid 
  SET ori.FDDBR = nosense.NAME,
  ori.FDDBRZJHM = nosense.idcardno;