场景:
有1.2亿条问答数据,相同问题的不同答案为不同条的数据,且该表数据逐日递增;
第三方需求(不合理):
将问题、答案数据分别放入问题表、答案表;
问题表的主键为整数,在答案表中,每行数据有相应的问题表的主键值;
为加快写入速度,不去问题表查找主键id,而在写库前,由脚本生成问题表的主键id,分别写入问题表、答案表;
生成算法:
11位时间戳+4位随机数
注意:时间戳至少11位;(千年代码)
mktime2date(1543400352) #2018-11-28 18:19:12
mktime2date(2543400352)
mktime2date(11543400352)
2018-11-28 18:19:12
2050-08-06 20:05:52
2335-10-19 12:05:52
取19位
while True:
s = str(time.time()).replace('.', '')[0:11] + str(random.random()).replace('0.', '')[0:8]
print(len(s), ':', s)
sql = 'INSERT INTO testtab (id,v) VALUES ({},{});'.format(s, s)
mysql_write(sql, mysql_key=mysql_key) bigint 2**32 /2 最多20位 实际越限制,取19位
CREATE TABLE `testtab` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`v` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9223372036854775807 DEFAULT CHARSET=utf8;
id v
1543481843334780969 1543481843334780969
1543481843635608877 1543481843635608877
1543481843922917607 1543481843922917607
1543481844262030440 1543481844262030440
1543481844454898236 1543481844454898236
1543481844753212767 1543481844753212767
1543481845071223819 1543481845071223819
1543481845310268788 1543481845310268788
1543481845574891236 1543481845574891236
1543481845801856854 1543481845801856854
1543481846122573779 1543481846122573779
1543481846437020403 1543481846437020403
1543481846688148132 1543481846688148132
1543481846961211022 1543481846961211022
1543481847216052080 1543481847216052080
1543481847589641016 1543481847589641016
1543481847709827395 1543481847709827395
1543481848042075766 1543481848042075766
1543481848361608572 1543481848361608572
1543481848613226664 1543481848613226664
1543481848829092584 1543481848829092584
1543481849104387422 1543481849104387422
def gen_mysql_pk_bigint():
s = str(time.time()).replace('.', '')[0:11] + str(random.random()).replace('0.', '')[0:8]
if len(s) < 19:
s = '{}{}'.format(s, ''.join(['9' for i in range(8)]))[0:19]
return s C:\Users\sas\.PyCharm2017.2\system\python_stubs\-1603771140\_random.py
def random(self): # real signature unknown; restored from __doc__
""" random() -> x in the interval [0, 1). """
pass
import time, random def gen_mysql_pk_bigint():
# int(time.time())
# 13=11+2
s0=random.random()
s1, s2 = str(time.time()).replace('.', '')[0:13], str(s0).replace('0.', '')[0:6]
s = s1 + s2
# 19-11=8 if len(s) < 19:
s = '{}{}'.format(s, ''.join(['9' for i in range(8)]))[0:19]
if '.' in s:
print('s0',s0)
print('s',s)
print(s1)
print(s2)
return s while True:
gen_mysql_pk_bigint() s0 4.542730178391796e-05
s 15435447395814.5427
1543544739581
4.5427
s0 3.257238433707066e-05
s 15435447395993.2572
1543544739599
3.2572
s0 4.646998949264791e-05
s 15435447396164.6469
1543544739616
4.6469
s0 2.2152567914712762e-05
s 15435447396202.2152
1543544739620
2.2152
s0 1.5478322555884105e-05
s 15435447396271.5478
1543544739627
1.5478