A good algorithm for generating an order number

前端 未结 10 1449
青春惊慌失措
青春惊慌失措 2021-01-31 06:27

As much as I like using GUIDs as the unique identifiers in my system, it is not very user-friendly for fields like an order number where a customer may have to repeat that to a

相关标签:
10条回答
  • 2021-01-31 07:08

    <Moan>OK sounds like a classic case of premature optimisation. You imagine a performance problem (Oh my god I have to access the - horror - database to get an order number! My that might be slow) and end up with a convoluted mess of psuedo random generators and a ton of duplicate handling code.</moan>

    One simple practical answer is to run a sequence per customer. The real order number being a composite of customer number and order number. You can easily retrieve the last sequence used when retriving other stuff about your customer.

    0 讨论(0)
  • 2021-01-31 07:10

    You could base64-encode a guid. This will meet all your criteria except the "numeric values only" requirement.

    Really, though, the correct thing to do here is let the database generate the order number. That may mean creating an order template record that doesn't actually have an order number until the user saves it, or it might be adding the ability to create empty (but perhaps uncommitted) orders.

    0 讨论(0)
  • 2021-01-31 07:12

    One simple option is to use the date and time, eg. 0912012359, and if two orders are received in the same minute, simply increment the second order by a minute (it doesn't matter if the time is out, it's just an order number).

    If you don't want the date to be visible, then calculate it as the number of minutes since a fixed point in time, eg. when you started taking orders or some other arbitary date. Again, with the duplicate check/increment.

    Your competitors will glean nothing from this, and it's easy to implement.

    0 讨论(0)
  • 2021-01-31 07:16

    One solution would be to take the hash of some field of the order. This will not guarantee that it is unique from the order numbers of all of the other orders, but the likelihood of a collision is very low. I would imagine that without "doing a round trip to the database" it would be challenging to make sure that the order number is unique.

    In case you are not familiar with hash functions, the wikipedia page is pretty good.

    0 讨论(0)
提交回复
热议问题