生成唯一的 10 位数字

发布于 2024-11-15 02:27:58 字数 253 浏览 1 评论 0原文

我想生成发票的客户 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

耀眼的星火 2024-11-22 02:27:58

我建议使用 AUTO_INCRMENT 列并将该值设置为 10 位数字。您可以将其作为表中的唯一列,如下所示,或者更实际地为您的发票表 ID 提供种子。

CREATE TABLE tablename (
  id bigint unsigned not null auto_increment,
  primary key(id),
  auto_increment=1000000000
);

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.

CREATE TABLE tablename (
  id bigint unsigned not null auto_increment,
  primary key(id),
  auto_increment=1000000000
);
通知家属抬走 2024-11-22 02:27:58

实际上,原因并不那么明显,除非您只是不想让您的客户知道客户 ID 太少,以至于他们的 ID 都是一位数:-)

顺便说一句,客户 ID 通常是在添加客户时生成的客户而不是开具发票。如果您指的是发票号码,那就不同了,但推理是一样的。

要么使用具有合适的较低 ID(例如 314159)的虚拟条目填充表,然后使用类似的内容:

insert into test (number) select max(number)+1 from test

或使用具有合适起始值的自动递增键(同样,该值取决于您,但您应该选择相对“非圆形”)。

有时,我会在想要完全控制分配的值(包括轻松更改它们的能力)的情况下使用前者,但更强大的解决方案可能是自动增量解决方案。

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:

insert into test (number) select max(number)+1 from test

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.

溺ぐ爱和你が 2024-11-22 02:27:58
ALTER TABLE my_invoice_table auto_increment=1000000001

递增发票号码很好 - 它们只需是唯一的,而不是随机的。

ALTER TABLE my_invoice_table auto_increment=1000000001

Incrementing invoice numbers are fine - they only have to be unique, not random.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文