生成唯一的 10 位数字
我想生成发票的客户 ID,因此出于显而易见的原因不想从 1 开始计数。在MySQL中你能生成一个唯一的随机数吗?
我知道 RAND() 函数,但它不能保证唯一性。正确的做法是什么?
不起作用:
INSERT INTO test (number) VALUES (FLOOR(0 + (RAND() * 9999999999)));
PS:服务器端我使用 PHP 并使用 FPDF 生成发票。
I want to generate customer ids for invoices and thus don't want to start counting from 1 for obvious reasons. In MySQL can you generate a random number that is unique?
I know about the RAND() function, but it does not guarantee uniqueness. What's the right approach for this?
Doesn't work:
INSERT INTO test (number) VALUES (FLOOR(0 + (RAND() * 9999999999)));
PS: Server side I'm using PHP and generate invoices using FPDF.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议使用
AUTO_INCRMENT
列并将该值设置为 10 位数字。您可以将其作为表中的唯一列,如下所示,或者更实际地为您的发票表 ID 提供种子。I suggest an
AUTO_INCREMENT
column and seed the value at 10 digits. You could have it be the only column in the table, like below, or more practically seed your invoice table id.实际上,原因并不那么明显,除非您只是不想让您的客户知道客户 ID 太少,以至于他们的 ID 都是一位数:-)
顺便说一句,客户 ID 通常是在添加客户时生成的客户而不是开具发票。如果您指的是发票号码,那就不同了,但推理是一样的。
要么使用具有合适的较低 ID(例如 314159)的虚拟条目填充表,然后使用类似的内容:
或使用具有合适起始值的自动递增键(同样,该值取决于您,但您应该选择相对“非圆形”)。
有时,我会在想要完全控制分配的值(包括轻松更改它们的能力)的情况下使用前者,但更强大的解决方案可能是自动增量解决方案。
Actually, the reasons aren't that obvious unless it's simply that you don't want your customers to know there are so few that they all have one-digit IDs :-)
As an aside, the customer ID is usually generated when adding a customer rather than doing an invoice. If you meant an invoice number, that's different, but the reasoning will be the same.
Either populate the table with a dummy entry with a suitable lower ID (314159 for example) then use something like:
or use an auto incrementing key with a suitable starting value (again, this value is up to you but you should choose something relatively "non-round").
I've sometimes used the former for situations where I want total control over what values are assigned (including the ability to easily change them) but a more robust solution would probably be the auto-increment one.
递增发票号码很好 - 它们只需是唯一的,而不是随机的。
Incrementing invoice numbers are fine - they only have to be unique, not random.