mysql functions ,LAST_INSERT_ID() 或 自定义主键

发布时间 2023-06-01 17:05:45作者: zno2

http://dev.mysql.com/doc/refman/5.6/en/information-functions.html

 

LAST_INSERT_ID()  这个值如果各个table 都有一个 自增的 id,那么各个table用各自的 LAST_INSERT_ID()

 

 

自定义:

# 固定前缀(2位)+ 时间戳(13位)+ 随机数(7位)
SELECT
        CONCAT(
            'AB', # 固定前缀 
            FLOOR(unix_timestamp(CURRENT_TIMESTAMP(3)) * power(10, 3)), # 时间戳,见 Java System.currentTimeMillis()
            LPAD(floor(rand() * power(10, 7)), 7, '0' ) # [0000000,9999999] or [0000000,10000000)
        );

 

 

# https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_floor
# https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_rand
# rand(10) ====>   [0,10)
# [0000000,9999999]
SELECT
    LPAD(
        floor(rand() * power(10, 7)),
        7,
        '0'
    )