SQL Server 数据库中的排序列表
我想知道是否可以/很好地在数据库中维护排序列表。
例如,我有一个优先级为 1~100 的项目列表。每次插入时,数据库都可以将其插入到适当的位置,这样当我调用 .select(20)
时,数据库可以返回优先级最高的前 20 项。
I was wondering if it is possible/good to maintain a sorted list in database.
For example, I have a list of items with priority 1~100. Every time I insert, the database can insert it into proper position, so that when I call .select(20)
, the database can return me the first 20 items with the highest priority.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加一个名为优先级的字段。适当地填充数据并按其排序,然后根据您的数据库选择前 20 个,例如
或
为该字段添加索引可能也是一个好主意。
这是一个非常持久的解决方案。任何其他利用行在表中物理存储顺序的解决方案都将非常脆弱。
Add A field called priority. Fill it with data appropriately and sort by it and depending on your database select the top 20 e.g.
or
Adding an index for the field would probably be a good idea as well.
This is a very durable solution. Any other solution that takes advantage of the order the rows are physically stored in the table would be very fragile.
请参阅 @Conrad Frix 的答案,发现这确实是可能的(使用窗口函数 ROW_NUMBER() 是另一种方法,它具有标准 SQL 的优点并在 SQL Server 中受支持)。请注意,这会向表中添加一列(如果您愿意的话,这是相关变量的属性),这不是“排序列表”,但似乎是您所需要的。
是个好主意吗?显然,如果这是您的应用程序/企业的要求,那么维护数据库中的值确实是合适的。
请注意,如果您有 100 行具有唯一
priority
属性值 1-100,并且您需要INSERT
一个值,例如priority = 55
,现有值 55-100 需要加一,数据库不会为您执行此操作,除非您在数据库对象中编写了程序代码来执行此操作(例如触发器)。如果您只需要管理 INSERT(而不是 UPDATE 或 DELETE),那么可能更好的方法是从更大的开始例如,您最初的 100 行的优先级值可以为 1000、2000、3000、...100000。现在,通过为其分配属性priority = 54500
,与之前相同的INSERT
可以在 54000 和 55000 之间移动,而无需重新分配任何值。See @Conrad Frix's answer to discover that it is indeed possible (using the windowed function
ROW_NUMBER()
is another approach that has the advantage of being Standard SQL and supported in SQL Server). Note that this adds a column to a table (an attribute to a relvar, if you will), which isn't a 'sorted list' but seems to be what you require.Is a good idea? Clearly, if this is a requirement on you application/enterprise then it is indeed appropriate to maintain the values in the database.
Note that if you have 100 rows with unique
priority
attribute values 1-100 and you need toINSERT
a value at, say,priority = 55
, the existing values 55-100 would need to be incremented by one and the database will not do that for you unless you have written procedural code in a database object to do so (e.g. a trigger). If you only have to manageINSERT
s (and notUPDATE
s norDELETE
s) then prehaps a better approach would be to start off with larger gaps e.g. your initial 100 rows could havepriority
values 1000, 2000, 3000,...100000. Now the sameINSERT
as before can go between 54000 and 55000 by assigning it the attributepriority = 54500
without the need to reassign any values.