数据库:如何对 GUID 进行排序?
我的主键使用 guid。
如何对 GUID 进行排序?
我创建一个日期时间列并记录日期时间戳怎么样,然后我可以按日期时间排序?这是最好的方法吗?或者有更好的方法吗?
My primary key uses guid.
How do I sort GUID?
What about I create a datetime column and record a datetime stamp, I could then sort by datetime? is this the best way to do it? or are there better ways?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Guid 顾名思义,是一个唯一的标识符。同一性并不意味着顺序,它只是为您提供了一种方法来确定两件事是否应该相同。为了排序,您需要确定比其他事物更大或更小意味着什么。从你的问题来看,排序似乎应该基于创建时间;指南不会帮助你。
A Guid is just what the name implies, a unique identifier. Identity doesn't imply order, it just gives you a way to determine whether 2 things are supposed to be identical. In order to sort, you need to determine what it means to be greater or maller than something else. From your question, it seems that sorting should be based on creation time; Guids won't help you with that.
死灵术。
GUID 只是随机数,它们没有顺序性(除非您使用equentialuid - 但它会在计算机重新启动后重新启动,因此几乎毫无意义)。
这就是 GUID 的实际排序方式:
代码不言而喻,神奇的部分是:
完整代码:
Necromancing.
GUIDs are just random numbers, there is no sequentiality in them (unless you use sequentialuid - but it restarts once the computer restarts, so it's pretty much pointless).
This is how GUIDs are actually sorted:
The code speaks for itselfs, the magical parts are:
Full code:
我会选择将 int (或 bigint)列设置为身份。每次插入一行时,标识都会增加。您可以对此列进行排序,以按照插入的顺序获取行。
I would go with an int (or bigint) column set up as an identity. Every time a row is inserted the identity will increment. You can sort on this column to get rows in the order they were inserted.
你想做什么?按插入日期排序?为此,您确实需要一个日期时间(或其变体之一)字段,因为 guid 和自动增量键都不能保证顺序,只能保证唯一性
阅读此内容以获取更多信息:主键排序
What are you trying to do? sort by insert date? for that you indeed do need a datetime (or one of its variants) field since both guids and auto incr keys can never guarantee order, only uniqueness
Read this for more information: Primary Key Sorting